Search code examples
c#.net.net-coretimedatetime-format

How to subtract time (HHH:MM)


I want to Subtract two time strings that I read from an excel sheet, for example 150:24 and 124:30.

The time format is HHH:MM in the excel sheet. How can I subtract these two strings in C#?

I can not illustrate the data format! also I can not write true code for this issue.


Solution

  • You can calculate the times difference based on minutes. Then convert to any format you want...

    var s1 = "150:24".Split(':');
    var s2 = "124:30".Split(':');
    
    var diffMinutes= int.Parse(s1[0]) * 60 + int.Parse(s1[1]) - int.Parse(s2[0]) * 60 - int.Parse(s2[1]);
    Console.WriteLine("difference in minutes: " +diffMinutes);  
    //difference in minutes: 1554
    
    Console.WriteLine("difference in HHH:MM: "+ diffMinutes/60 + ":"+diffMinutes%60); 
    //difference in HHH:MM: 25:54
    
    TimeSpan t= TimeSpan.FromMinutes(result);
    Console.WriteLine(t); 
    //1.01:54:00