Warm tip: This article is reproduced from serverfault.com, please click

How to format a TimeSpan for hours not days

发布于 2011-04-18 14:00:29

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.

Questioner
Ralph Shillington
Viewed
0
Chris Shouts 2011-04-18 22:17:25

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.