Home > other >  How to subtract time (HHH:MM)
How to subtract time (HHH:MM)

Time:12-18

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.

CodePudding user response:

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`); 
//difference in HHH:MM: 25:54

TimeSpan t= TimeSpan.FromMinutes(result);
Console.WriteLine(t); 
//1.01:54:00

CodePudding user response:

TimeSpan.Parse unfortunately does not work is the hour part is > 23. But of course it is possible to split on the ':', convert the hour and minute parts to integers separately and construct a TimeSpan from it:

public static TimeSpan ParseHoursAndMinutes(string s)
{
  // NOTE: no error checking!
  var parts = s.Split(':');
  var hours = int.Parse(parts[0]);
  var minutes = int.Parse(parts[1]);
  return new TimeSpan(hours, minutes, 0);
}

var diff = ParseHoursAndMinutes("150:24") - ParseHoursAndMinutes("124:30");
Console.WriteLine(diff); // => 1.01:54:00
  • Related