TimeSpan String Formatting
Asked Answered
R

3

9

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

Rascon answered 31/1, 2013 at 9:7 Comment(1)
Can you show the expected results?Bonedry
S
11

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.

Septime answered 31/1, 2013 at 9:20 Comment(4)
Thanks Tim, appreciate it.Rascon
It's weird, I think the issue must come with the DateTime that I am deducting from DateTime.Now in my app. As in exaples above, my code does work.Rascon
@Derek: Edited my answer to provide a way on 3.5 by converting the TimeSpan to DateTime. The examples work because they simply add whole hours, then you have no rounding issue with fractional seconds.Septime
+1 Tim, nice explanation, TimeSpan.ToString doesn't have an overload for string format in .Net 2.0.Investment
I
7

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
Investment answered 31/1, 2013 at 9:16 Comment(7)
I think he may want the time rounded to 06:00:00.Honorable
But have a look at ideone: ideone.com/FMye8j I assume that it's framework dependent with string.Format.Septime
@TimSchmelter Where has your answer gone?Rascon
@Derek: deleted since i wasn't sure what causes your issue and why it works sometimes.Septime
@Derek: Added it again. It was a breaking change from 3.5 to 4.0Septime
This example does only work because you subtract 6 hours, hence there is no fractional seconds part in the TimeSpan. On 3.5 it doesn't work as shown on ideone(mono).Septime
@TimSchmelter, yes it doesn't work with .Net 2.0 , But it TimeSpan TimeDifference = DateTime.Now - DateTime.Now.AddHours(-6).AddSeconds(-20); does the formatting on .Net 4.0Investment
I
5

Works fine for me.

For example, this program:

using System;

namespace Demo
{
    public static class Program
    {
        private static void Main(string[] args)
        {
            DateTime then = new DateTime(2013, 1, 30, 0, 1, 3);
            TimeSpan ts = DateTime.Now - then;

            Console.WriteLine(ts.ToString());
            Console.WriteLine(ts.ToString(@"hh\:mm\:ss"));
            Console.WriteLine(string.Format(@"{0:hh\:mm\:ss}", ts));

            // Or, with rounding:
            TimeSpan rounded = TimeSpan.FromSeconds((int)(0.5 + ts.TotalSeconds));
            Console.WriteLine(rounded.ToString(@"hh\:mm\:ss"));
        }
    }
}

Outputs something like:

1.09:20:22.5070754
09:20:22
09:20:22
09:20:23 <- Note rounded up to :23
Instauration answered 31/1, 2013 at 9:18 Comment(3)
Just works because you use at least .NET 4 instead of OP's 3.5Septime
So rounding as in my example above should fix it for .Net 3.5 too, I think.Instauration
Yes, i think so. It just ignores the fact that everything else doesn't work for OP (or anybody using a .NET version lower than4 )Septime

© 2022 - 2024 — McMap. All rights reserved.