1

我想用条件计算 DateTime 持续时间:IF "STATUSIN" > 08:00:00 then "LATECOME" = "STATUSIN" - 08.00.00 我一直在尝试这段代码,但它不起作用。

DataTable dtDaily = new DataTable();
string time1 = "08:00:00";
var result = Convert.ToDateTime(time1);
string test = result.ToString("hh:mm:ss");

foreach (DataRow pRow in dtDaily.Rows)
{
   DateTime.ParseExact(pRow["STATUSIN"].ToString(), "hh:mm:ss", CultureInfo.InvariantCulture);
   if (pRow["STATUSIN"] > time1)
   {
      pRow["LATECOME"] = pRow["STATUSIN"] - time1.ToString();
   }
}

这是我在表中显示值的代码:

<asp:Repeater ID="rptrSUMMARYDATA" runat="server">
    <HeaderTemplate>
        <table class="table">
            <thead>
                <tr>
                    <th>IN</th>
                    <th>LATECOME</th>
                </tr>
            </thead>
            <tbody>
    </HeaderTemplate>
    <ItemTemplate>
        <tr>
            <td><%# Eval("STATUSIN") %></td>
            <td><%# Eval("LATECOME") %></td>
        </tr>
    </ItemTemplate>
    <FooterTemplate>
            </tbody>
        </table>
    </FooterTemplate>
</asp:Repeater> 
4

2 回答 2

1

更改代码

 string time1 = "08:00:00";
DateTime.ParseExact(pRow["STATUSIN"].ToString(), "hh:mm:ss", CultureInfo.InvariantCulture);
if (pRow["STATUSIN"] > time1)
{
    pRow["LATECOME"] = pRow["STATUSIN"] - time1.ToString();
}

替换代码

DateTime time1 = DateTime.Parse("08:00:00");
 Datetime d=DateTime.ParseExact(pRow["STATUSIN"].ToString(), "hh:mm:ss", CultureInfo.InvariantCulture);
   if (d > time1)
   {
      pRow["LATECOME"] =d - time1.ToString();
   }
于 2020-02-18T07:39:26.117 回答
1

您的代码不起作用的原因是由于字符串数据的比较。您可以检查字符串是否大于彼此,但不能检查您的想法。

如果要比较两个日期,则必须先将字符串转换为 DateTime,然后检查哪个日期早于另一个日期。

DataTable dtDaily = new DataTable();

// If you want to compare the Time, use TimeSpan
TimeSpan time1 = new TimeSpan(8, 0, 0);

foreach (DataRow pRow in dtDaily.Rows)
{
   if (pRow.Field<DateTime>("STATUSIN").TimeOfDay > time1)
   {
      // This will ONLY be the time portion.. not the full datetime. Notice the 
      // parenthesis around the the statement on the right. You want to convert the resulting
      // Time (after subtraction) to string.
      pRow["LATECOME"] = (pRow.Field<DateTime>("STATUSIN").TimeOfDay  - time1).ToString();
   }
}

pRow.Field<DateTime>("field)获取数据的字符串表示形式并将其转换为 DateTime。这类似于DateTime.Parse(pRow["field"])但取消了进行转换的步骤。


请参阅有关 TimeSpan 的文档

public TimeSpan (int hours, int minutes, int seconds);

于 2020-02-18T13:34:40.330 回答