简体   繁体   English

如果第二天是第二天,则两个时间跨度之间的差额

[英]The difference between 2 timespans if the second one is on the next day

Let's say I have 2 timespans (24h format) in C#: 假设我在C#中有2个跨度(24h格式):

TimeSpan start = TimeSpan.Parse("22:11:00");
TimeSpan end = TimeSpan.Parse("01:54:12");
TimeSpan duration = end - start;

The problem is that the duration in this case is a negative number, far from the correct result. 问题在于这种情况下的持续时间为负数,与正确的结果相去甚远。 How to get the correct duration? 如何获得正确的持续时间?

Take a look at the following Unit test 看看下面的单元测试

[DataRow("16:00", "01:00", "09:00")]
[DataRow("16:00", "21:00", "05:00")]
public void CalculateDuration(string open, string close, string expected) {
    var begin = TimeSpan.Parse(open);
    var end = TimeSpan.Parse(close);

    var actual = end < begin ? (TimeSpan.FromHours(24) - begin) + end : end - begin;

    Assert.AreEqual(TimeSpan.Parse(expected), actual);
}

您可以使用Duration()方法:

TimeSpan duration = (start - end).Duration();
TimeSpan duration = end - start;

start - end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM