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

Jürgen Steinblock picture Jürgen Steinblock · Aug 23, 2010 · Viewed 30.8k times · Source

I want to display the elapsed time between two dates in a string.

Let's say I have the following code:

DateTime date1 = DateTime.Now();
System.Threading.Thread.Sleep(2500);
DateTime date2 = DateTime.Now();

TimeSpan elapsed = date2.substract(date1);
Console.WriteLine("> {0:hh:mm:ss}", elapsed);

What I expect:

> 00:00:03

What I get:

> 00:00:02.5002500

Is there a way to use the String.Format function to only return full seconds?
I also tried to remove the decimal places with:

elapsed = elapsed.Substract(TimeSpan.FromMiliseconds((double)Timespan.Miliseconds);

But that doesn't work either since elapsed.Miliseconds returns 500 as an Integer.

Answer

Doctor Jones picture Doctor Jones · Sep 23, 2010

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.