eagle779 eagle779 - 1 year ago 71
C# Question

Why does TimeSpan.FromMinutes return incorrect total hours value

When I run this on .netfiddle I expected a result of 182 hours hours and 30 minutes. But instead I get 183 hours - why is this? It's as if daylight saving had happened?

TimeSpan tsTime = TimeSpan.FromMinutes((double)10950);
Console.WriteLine(tsTime.TotalHours.ToString("00") + ":" + tsTime.Minutes.ToString("00"));

Answer Source

Because 30 minutes is 0.5 hour so when you are converting it using ToString() its make it as full hour. So rounding it can solve the problem

If you want rounded output then round it as which give you 182:30

TimeSpan tsTime = TimeSpan.FromMinutes((double)10950);
Console.WriteLine(((int)tsTime.TotalHours).ToString("00") + ":" + tsTime.Minutes.ToString("00"));

and if you want actual then it will give 182.5:30

Console.WriteLine(tsTime.TotalHours+ ":" + tsTime.Minutes);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download