Reputation: 9767
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?
Upvotes: 1
Views: 742
Reputation: 6327
Check out http://msdn.microsoft.com/en-us/library/ee372286.aspx.
Upvotes: 0
Reputation: 887453
Until .Net 4.0, TimeSpans do not support format strings.
In .Net 4.0, the format strings are documented.
Upvotes: 6
Reputation: 18387
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]
Upvotes: 7