代码之家  ›  专栏  ›  技术社区  ›  user726720

时间跨度比较

  •  0
  • user726720  · 技术社区  · 7 年前

    我有以下时间样本:

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

    我有一个样品 00:31 ( nextday

    if (cdnTime > nextNode)
    {
       //dosomething
     }
    

    cdnTime 这是你的电话号码 00:31 00:31 大于除 00:52 所以我需要if语句在到达 00:52

    1 回复  |  直到 7 年前
        1
  •  1
  •   Christoph Sonntag    7 年前

    是的,你需要告诉我这是新的一天。您可以使用DateTime,但也可以使用额外的一天来初始化timespan—它提供了 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