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.
Change the
to
.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: