首页 > 解决方案 > 在c#中计算时间差的正确方法

问题描述

我正在计算工人的加班时间。我已将数据加载到 datagridview 中。我将列命名为 startot(排名第 5)和 endot(排名第 6)。这是我计算持续时间的代码

 TimeSpan duration = new TimeSpan();
 foreach (DataGridViewRow row in attenViewGrid.Rows)
 {
     string start = row.Cells[5].Value.ToString();
     string end = row.Cells[6].Value.ToString();
     duration += DateTime.Parse(end).Subtract(DateTime.Parse(start));
  }

现在我在上午 10:00 到第二天上午 9:00 开始加班时遇到问题。随时间推移计算​​的最佳方法是什么。

标签: c#visual-studiowinformsvisual-studio-2010

解决方案


您应该在表格单元格中指定日期和时间,当您通过解析时间字符串创建日期时间对象时,它会设置固定日期。

否则,您可以设置一天增量的条件:

 TimeSpan duration = new TimeSpan();
 foreach (DataGridViewRow row in attenViewGrid.Rows)
 {
     string start = row.Cells[5].Value.ToString();
     string end = row.Cells[6].Value.ToString();

     if(DateTime.Parse(end).Compare(DateTime.Parse(start)) < 0) 
         duration += Timespan.FromDays(1);

     duration += DateTime.Parse(end).Subtract(DateTime.Parse(start));
  }

推荐阅读