Try to parse string to TimeSpan using formats, culture, and styles in CSharp
Description
The following code shows how to try to parse string to TimeSpan using formats, culture, and styles.
Example
//from www. j ava 2 s . c om
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
string[] inputs = { "3", "16:42", "1:6:52:35.0625",
"1:6:52:35,0625" };
string[] formats = { "%h", "g", "G" };
TimeSpan interval;
CultureInfo culture = new CultureInfo("fr-FR");
// Parse each string in inputs using formats and the fr-FR culture.
foreach (string input in inputs) {
if(TimeSpan.TryParseExact(input, formats, culture,
TimeSpanStyles.AssumeNegative, out interval))
Console.WriteLine("{0} --> {1:c}", input, interval);
else
Console.WriteLine("Unable to parse {0}", input);
}
}
}
The code above generates the following result.