Hello,
I was looking for C# objects and properties to find the time difference between two dates in hh:mm format.
date1 = " 12/21/2007 10:20 pm "
date2 = " 12/22/2007 10:35 pm"
My result should be time difference between date2 and date1 which would be in the format of 24:15(hh:mm)
I used Timespan and DateTime classes but they return either the total hours or total minutes. But, not the time difference in hh:mm format.
Any help will be appreciated.
Thanks,
Prasanna.
To find Time Difference using C#
4 Answers
Know the answer? Post it. Somebody with the same question will find it here.

AlanRank #669 · 3.6K reputationPosted Jul 11, 2007, 12:58 PM EDT
DateTime dt1 = DateTime.Parse(date1);
DateTime dt2 = DateTime.Parse(date2);
TimeSpan ts = dt2 - dt1;
string diff = (ts.Days * 24 + ts.Hours).ToString("00") + ":" + ts.Minutes.ToString("00");
Console.WriteLine(diff); // 24:15 hopefully
I assume you're not going to be using dates more than a few days apart?
prasanna kumar12 reputationPosted Jul 11, 2007, 1:18 PM EDT
I will be using months of data. So, I would appreciate if you could get me the code.
Thanks,
prasanna.
AlanRank #669 · 3.6K reputationPosted Jul 11, 2007, 2:05 PM EDT
I was worried that if the number of hours went above 99, that the Int32.ToString("00") method might truncate it to 2 digits but I've just tried it and it still works fine.
prasanna kumar12 reputationPosted Jul 12, 2007, 3:48 AM EDT
Alan,
The code worked fine. Thank you very much,
Prasanna.