Ralph Shillington
Ralph Shillington

Reputation: 21098

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.

Upvotes: 13

Views: 21024

Answers (3)

Consule
Consule

Reputation: 1239

Another possibility is:

TimeSpan day = new TimeSpan(2,1,20,0); // 2.01:20:00
Console.WriteLine("{0} hours {1} minutes", (int)day.TotalHours, day.Minutes);

Console will show:

49 hours 20 minutes

Upvotes: -1

ChrisF
ChrisF

Reputation: 137148

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.

Upvotes: 10

Chris Shouts
Chris Shouts

Reputation: 5427

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.

Upvotes: 15

Related Questions