Search code examples
c#datetimetimespan

Timespan Compare


I have following time samples:

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

I have a sample 00:31 (nextday) that needs to be compared and check if its less then the above samples.

if (cdnTime > nextNode)
{
   //dosomething
 }

cdnTime here is the 00:31 and nextNode is the above given multiple samples. Time 00:31 is greater then all samples except 00:52 so I need the if statement to be false until it reaches 00:52. How do I achieve this. Keeping in mind the time samples switch to next day, do I need to make it as DateTime and then compare or is there any way of comparison with TimeSpan without dates.


Solution

  • Yes you need to somehow tell that it's another day. You can either use a DateTime, but you could also initialize a timespan with an additional day - it provides a Parse-method for this:

    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);
        }
    }
    

    Another option would be to add the day afterwards:

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

    You can try it out here: https://dotnetfiddle.net/k39TIe