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
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.
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.
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".
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.
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With