Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a TimeSpan for hours not days

The following code

Console.WriteLine("{0:%h} hours {0:%m} minutes", 
                   new TimeSpan(TimeSpan.TicksPerDay));

produces this output:

0 hours 0 minutes

What I would like is this output:

24 hours 0 minutes

What am I missing in this format string?

P.S. I know that I could manually bust up the TimeSpan into days and hours, and multiply the two but would rather use a custom format string, as these timespans are being displayed in a silverlight datagrid and people are expecting to see horus, not days.

like image 816
Ralph Shillington Avatar asked Apr 18 '11 14:04

Ralph Shillington


1 Answers

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.

like image 92
Chris Shouts Avatar answered Oct 02 '22 15:10

Chris Shouts