Use String.Format on a TimeSpan to output full seconds without milliseconds

Change the

Console.WriteLine("> {0:hh:mm:ss}", elapsed);

to

Console.WriteLine("> {0:hh\\:mm\\:ss}", elapsed);

.Net 4 allows you to use custom format strings with Timespan. You can find a full reference of available format specifiers at the MSDN Custom TimeSpan Format Strings page.

You need to escape the ":" character with a "\" (which itself must be escaped unless you're using a verbatim string).

This excerpt from the MSDN Custom TimeSpan Format Strings page explains about escaping the ":" and "." characters in a format string:

The custom TimeSpan format specifiers do not include placeholder separator symbols, such as the symbols that separate days from hours, hours from minutes, or seconds from fractional seconds. Instead, these symbols must be included in the custom format string as string literals. For example, "dd.hh:mm" defines a period (.) as the separator between days and hours, and a colon (:) as the separator between hours and minutes.


Unfortunately it's not possible to format a TimeSpan in the same way as a DateTime value. You can however do a quick conversion because both TimeSpan and DateTime store their value as ticks (in the Ticks property).

In your code that would look like this:

Console.WriteLine("> {0:hh:mm:ss}", new DateTime(elapsed.Ticks));

UPDATE: This applies to .NET 3.5 and earlier, .NET 4 does support formatting TimeSpans.