Fickle Bits

You're doing it wrong.

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

Comments