Convert TimeSpan to string using the specified format in CSharp
Description
The following code shows how to convert TimeSpan to string using the specified format.
Example
using System;//from w w w.ja v a 2 s . c o m
public class Class1
{
public static void Main()
{
TimeSpan[] spans = { TimeSpan.Zero, new TimeSpan(-14, 0, 0, 0, 0),
new TimeSpan(1, 2, 3),
new TimeSpan(1, 0, 0, 0, 250),
new TimeSpan(99, 23, 59, 59, 999),
new TimeSpan(3, 0, 0),
new TimeSpan(1, 0, 1, 0, 25) };
string[] fmts = { "c", "g", "G", @"hh\:mm\:ss", "%m' min.'" };
foreach (TimeSpan span in spans)
{
foreach (string fmt in fmts)
Console.WriteLine("{0}: {1}", fmt, span.ToString(fmt));
}
}
}
The code above generates the following result.