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

Viewed 33260

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.

8 Answers
Timespan duration = endDateTime - startDateTime;
duration.ToString("hh\\:mm\\:ss");
Related