Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TimeSpan String Formatting

I have a Timespan that I need to output in a particular format as shown below :-

TimeSpan TimeDifference = DateTime.Now - RandomDate;

I'm formatting the TimeSpan like this :-

string result = string.Format(@"{0:hh\:mm\:ss}", TimeDifference);

The Result will look something like this :-

"00:16:45.6184635"

How do I round those seconds to 0 decimal places?

Expected Result = 00:16:46

Thanks

like image 845
Derek Avatar asked Jan 31 '13 09:01

Derek


People also ask

What format is TimeSpan?

NET Framework 4. "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.

How to change TimeSpan format in C#?

We can get a TimeSpan object by subtracting two DateTime objects in C#. The following example prints a TimeSpan object. To do formatting of a TimeSpan object, use TimeSpan. ToString() method.

What is the string .format for date?

The full date long time ("F") format specifier For example, the custom format string for the invariant culture is "dddd, dd MMMM yyyy HH:mm:ss".

Is date and time a string?

A date and time format string is a string of text used to interpret data values containing date and time information. Each format string consists of a combination of formats from an available format type. Some examples of format types are day of week, month, hour, and second.


2 Answers

Your code works with .NET 4 but not with 3.5 since there was a breaking change on 4, TimeSpan now implements IFormattable (see below).

What you can do on 3.5 or lower is, convert the TimeSpan to DateTime and use ToString:

DateTime dtime = DateTime.MinValue.Add(TimeDifference);
string result = dtime.ToString(@"hh\:mm\:ss");

Here you can see the non-working + working version:http://ideone.com/Ak1HuD


Edit I think the reason why it works sometimes and sometimes not is that since .NET 4.0 TimeSpan implements IFormattable which seem to be used by String.Format.

like image 82
Tim Schmelter Avatar answered Oct 06 '22 21:10

Tim Schmelter


Your code should work fine (after removing minor syntax errors). Consider the following example:

TimeSpan TimeDifference = DateTime.Now - DateTime.Now.AddHours(-6);
string result = string.Format(@"{0:hh\:mm\:ss}", TimeDifference);
Console.WriteLine("TimeSpan: {0}", TimeDifference.ToString());
Console.WriteLine("Formatted TimeSpan: {0}", result);

Output:

TimeSpan: 05:59:59.9990235
Formatted TimeSpan: 05:59:59
like image 34
Habib Avatar answered Oct 06 '22 21:10

Habib