Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 927
Jürgen Steinblock Avatar asked Aug 23 '10 07:08

Jürgen Steinblock


People also ask

What is the format of a TimeSpan?

"c" is the default TimeSpan format string; the TimeSpan. ToString() method formats a time interval value by using the "c" format string. TimeSpan also supports the "t" and "T" standard format strings, which are identical in behavior to the "c" standard format string.

What is the format of TimeSpan in C#?

You can format a TimeSpan in the hh: mm: ss format in C#.


2 Answers

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.

like image 181
Doctor Jones Avatar answered Oct 02 '22 03:10

Doctor Jones


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.

like image 29
Marnix van Valen Avatar answered Oct 02 '22 03:10

Marnix van Valen