Parse string to TimeSpan using the specified culture-specific format in CSharp
Description
The following code shows how to parse string to TimeSpan using the specified culture-specific format.
Example
using System;//from ww w. j ava 2 s. c o m
using System.Globalization;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string[] values = { "6", "6:12", "6:12:14", "6:12:14:45",
"6.12:14:45", "6:12:14:45.3448",
"6:34:14:45" };
CultureInfo[] cultures = { new CultureInfo("en-US"),
new CultureInfo("ru-RU"),
CultureInfo.InvariantCulture };
string header = String.Format("{0,-17}", "String");
foreach (CultureInfo culture in cultures)
header += culture.Equals(CultureInfo.InvariantCulture) ?
String.Format("{0,20}", "Invariant") :
String.Format("{0,20}", culture.Name);
Console.WriteLine(header);
foreach (string value in values)
{
Console.Write("{0,-17}", value);
foreach (CultureInfo culture in cultures)
{
TimeSpan ts = TimeSpan.Parse(value, culture);
Console.WriteLine("{0,20}", ts.ToString("c"));
}
}
}
}
The code above generates the following result.