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?