c# - 在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 开始加班时遇到问题。随时间推移计算的最佳方法是什么。
解决方案
您应该在表格单元格中指定日期和时间,当您通过解析时间字符串创建日期时间对象时,它会设置固定日期。
否则,您可以设置一天增量的条件:
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));
}
推荐阅读
- c# - 在c#上使用反射获取字段的值
- apache-spark - SPARK 如何在出错的情况下获取列名(FAILFAST 模式)?
- jmeter - 我有 JSR233 侦听器,在 JMeter 非 gui 模式下似乎被忽略了
- javascript - 最终结果中 javascript 中的颜色代码
- angular - Angular6如何将共享数据与同级服务绑定,以便每个实例都有自己的引用
- angular - 带有formarray的Angular 9动态控件无法正常工作
- android - KlarnaHybridSDK - 被“Notifying Native Hook”消息淹没 [ANDROID]
- vim - 防止 `mergetool` 和 `difftool` 在 `~/.vim/view` 中自动保存
- python-3.x - Grakn 1.6.0 中的 Java 堆空间问题
- android - 想要在 Constraintlayout 中更改条件时更改按钮位置