C# + Format TimeSpan

NOTE: This answer applies to .NET 4.0 only.

The colon character is a literal and needs to be wrapped in single quotes:

duration.ToString("mm':'ss")

From the MSDN documentation:

The custom TimeSpan format specifiers do not include placeholder separator symbols, such as the symbols that separate days from hours, hours from minutes, or seconds from fractional seconds. Instead, these symbols must be included in the custom format string as string literals.


Try this:

Console.WriteLine("{0:D2}:{1:D2}", duration.Minutes, duration.Seconds);

For some mysterious reason TimeSpan never got the ToString() overloads that support formatting until .NET 4.0. For earlier releases, as long as it is positive, you can hijack DateTime.ToString():

TimeSpan ts = new TimeSpan(0, 2, 8);
string s = new DateTime(ts.Ticks).ToString("mm:ss");

Tags:

C#