views:

86

answers:

3

Hi all!

While coding today, I noticed something odd with timespans and formatting strings. I was trying to print a timespan, for instance 01:03:37 as 1:03:37 (without the leading 0 for hours). So I used the format string h:mm:ss. This, however, gave me a leading 0. If I converted the TimeSpan to a DateTime and did the same thing again, the h formatting string worked as I expected.

A sample console program:

class Program
{
    static void Main(string[] args)
    {
        var time = new TimeSpan(01, 03, 37);

        var culture = new CultureInfo("sv-SE");

        Thread.CurrentThread.CurrentCulture = culture;
        Thread.CurrentThread.CurrentUICulture = culture;

        Console.WriteLine(time.ToString());

        Console.WriteLine(string.Format(culture, "{0:h:mm:ss}", time));
        Console.WriteLine(string.Format(culture, "{0:hh:mm:ss}", time));

        Console.WriteLine((new DateTime(time.Ticks)).ToString("h:mm:ss", culture));
        Console.WriteLine((new DateTime(time.Ticks)).ToString("hh:mm:ss", culture));

        Console.ReadKey();
    }
}

Output:

01:03:37
01:03:37  // <-- expected: 1:03:37
01:03:37
1:03:37
01:03:37

Why is the TimeSpan and DateTime behaving differently?

+7  A: 

Because your formatting string do not work for TimeSpan and TimeSpan.ToString() always returns (from MSDN):

A string that represents the value of this instance. The return value is of the form:

[-][d.]hh:mm:ss[.ff]

Orsol
+6  A: 

Until .Net 4.0, TimeSpans do not support format strings.

In .Net 4.0, the format strings are documented.

SLaks
A: 

Check out http://msdn.microsoft.com/en-us/library/ee372286.aspx.

Edward Leno
[Wrong](http://msdn.microsoft.com/en-us/library/ee372287.aspx)
SLaks
Thanks ... missed the 'h' info in the document (removed from answer).
Edward Leno