TimeSpan ToString format

Be aware of this when using the answer from Jon Skeet, with code like this:

// 12 days, 23 hours, 24 minutes, 2 seconds.
TimeSpan span = new TimeSpan(12, 23, 24, 2);
// 27 hours, 24 minutes, 2 seconds
TimeSpan span2 = new TimeSpan(27,24,2);

string format = span.ToString("h'h 'm'm 's's'");
string format2 = span2.ToString("h'h 'm'm 's's'");
Console.WriteLine(format);
Console.WriteLine(format2);
Console.ReadLine();

You get results like these:

23h 24m 2s
3h 24m 2s

The hour format can at maximum show 23 hours. It will not show 27 hours or convert the 12 days to hours, it will simply cut them off as if they never existed.

One way to fix this would be to create an extension that checks the length of the TimeSpan and creates formatting based on if the timespan is over a year, day, ect. Or you could simply always show days as well because they never cut off:

string newFormat = span.ToString("d'd 'h'h 'm'm 's's'");

Do note I am a beginner at programming. This is only coming from observations after I was lucky enough to notice this after having assumed it would show all hours. I'm saying this because I don't know if there is a better solution, like another hour format that can display endless hours.

I do however think this format is doing its intended functionality. You just have to be aware of it. Thus this post. Jon Skeet's answer never indicated that this format is to show only the hour property of a date type format where the hours can be at most 23.


Try:

myTimeSpan.ToString("h'h 'm'm 's's'")

(Note that even spaces need to be quoted - that's what was wrong with my first attempt.)

I'm assuming you're using .NET 4, of course - before that, TimeSpan didn't support custom format strings.

EDIT: As noted, this won't work beyond 24 hours. Also note that alternatives are available via Noda Time too :)

Tags:

C#

.Net