A Helpful Formatter for TimeSpan

I am doing a healthy amount of logging in a multi-threaded app, and I frequently need to output a TimeSpan value.  The default ToString() implementation for TimeSpan outputs the time in a 04:00:00 format, which isn’t as friendly to read as “4 hours”.

Here is a quick extension method that will give you this type of output. 

This code calls a Quanitify method, that is defined as:

…and the (naive) Pluralize() method looks like:

Notice that it only deals with 1 unit at a time, so if you have something like 36 hours it will treat it as 1.5 days (which is acceptable in my scenario).

The output looks like the table below:

TimeSpan.FromDays(1)

1 day

TimeSpan.FromDays(2)

2 days

TimeSpan.FromHours(36)

1.5 days

TimeSpan.FromHours(6)

6 hours

TimeSpan.FromHours(1)

1 hour

TimeSpan.FromMinutes(34)

34 minutes

TimeSpan.FromMinutes(1)

1 minute

TimeSpan.FromSeconds(70)

1.2 minutes

TimeSpan.FromMilliseconds(800)

800 milliseconds

#1 Jim Wild avatar
Jim Wild
12.07.2009
11:10 AM

Useful, cheers.


#2 Sergio Pereira avatar
Sergio Pereira
12.07.2009
5:49 PM

FYI, these gist code snippets don't show up in the RSS feed. I was looking for some download link until I came to the actual blog.


#3 benscheirman avatar
benscheirman
12.07.2009
10:09 PM

@sergio: this was my first post using gists. I'm not sure if I'll keep them if RSS readers won't see them. Thanks for the note.


Leave a Comment