How to format a TimeSpan for hours not days
According to MSDN, using %h
will show you
The number of whole hours in the time interval that are not counted as part of days.
I think you will need to use the TotalHours
property of the TimeSpan
class like:
TimeSpan day= new TimeSpan(TimeSpan.TicksPerDay);
Console.WriteLine("{0} hours {1} minutes", (int)day.TotalHours, day.Minutes);
Update
If you absolutely need to be able to achieve the stated format by passing custom formatters to the ToString
method, you will probably need to create your own CustomTimeSpan
class. Unfortunately, you cannot inherit from a struct
, so you will have to build it from the ground up.
There doesn't seem to be a format option for getting the total hours out of a TimeSpan
. Your best bet would be to use the TotalHours
property instead:
var mySpan = new TimeSpan(TimeSpan.TicksPerDay);
Console.WriteLine("{0} hours {1} minutes", (int)mySpan.TotalHours, mySpan.Minutes);
TotalHours
returns a double as it includes the fractional hours so you need to truncate it to just the integer part.