时间跨度比较

Timespan Compare

我有以下时间样本:

06:09
08:10
23:12
00:06   // next day
00:52

我有一个样本 00:31 (nextday) 需要比较并检查它是否小于上述样本。

if (cdnTime > nextNode)
{
   //dosomething
 }

cdnTime 这里是 00:31 而 nextNode 是上面给出的多个样本。时间 00:31 大于除 00:52 之外的所有样本,因此我需要 if 语句在达到 00:52 之前为假。我如何实现这一点。请记住时间样本切换到第二天,我是否需要将其设为 DateTime 然后进行比较,或者是否有任何方法可以与没有日期的 TimeSpan 进行比较。

是的,您需要以某种方式告诉我们又是新的一天。您可以使用 DateTime,但也可以使用额外的一天来初始化时间跨度 - 它为此提供了 Parse-method

using System;
using System.Globalization;             

public class Program
{
    public static void Main()
    {
        var cdnTime = TimeSpan.Parse("23:12", CultureInfo.InvariantCulture);
        var nextTime = TimeSpan.Parse("01.00:03", CultureInfo.InvariantCulture);

        Console.WriteLine(cdnTime.TotalMinutes);
        Console.WriteLine(nextTime.TotalMinutes);
        Console.WriteLine(cdnTime.CompareTo(nextTime));
        Console.WriteLine(cdnTime < nextTime);
    }
}

另一种选择是在之后添加一天:

var anotherTime = TimeSpan.FromMinutes(3);
anotherTime = anotherTime.Add(TimeSpan.FromDays(1));        
Console.WriteLine(anotherTime.TotalMinutes);

你可以在这里试试: https://dotnetfiddle.net/k39TIe