TimeSpan String Formatting

15,440

Solution 1

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.

Solution 2

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

Solution 3

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
Share:
15,440
Derek
Author by

Derek

Currently working as a software developer building enterprise solutions within the .Net Framework I have an interest in design patterns, best practice and new technologies.

Updated on June 04, 2022

Comments

  • Derek
    Derek almost 2 years

    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

    • Kaf
      Kaf over 11 years
      Can you show the expected results?
  • Jason
    Jason over 11 years
    I think he may want the time rounded to 06:00:00.
  • Tim Schmelter
    Tim Schmelter over 11 years
    But have a look at ideone: ideone.com/FMye8j I assume that it's framework dependent with string.Format.
  • Derek
    Derek over 11 years
    @TimSchmelter Where has your answer gone?
  • Tim Schmelter
    Tim Schmelter over 11 years
    @Derek: deleted since i wasn't sure what causes your issue and why it works sometimes.
  • Tim Schmelter
    Tim Schmelter over 11 years
    @Derek: Added it again. It was a breaking change from 3.5 to 4.0
  • Derek
    Derek over 11 years
    Thanks Tim, appreciate it.
  • Derek
    Derek over 11 years
    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.
  • Tim Schmelter
    Tim Schmelter over 11 years
    @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.
  • Tim Schmelter
    Tim Schmelter over 11 years
    Just works because you use at least .NET 4 instead of OP's 3.5
  • Tim Schmelter
    Tim Schmelter over 11 years
    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).
  • Habib
    Habib over 11 years
    +1 Tim, nice explanation, TimeSpan.ToString doesn't have an overload for string format in .Net 2.0.
  • Habib
    Habib over 11 years
    @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.0
  • Matthew Watson
    Matthew Watson over 11 years
    So rounding as in my example above should fix it for .Net 3.5 too, I think.
  • Tim Schmelter
    Tim Schmelter over 11 years
    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 )