Mega Code Archive

 
Categories / C# / Date Time
 

Parse strings to TimeSpan

using System; using System.Globalization; using System.Threading; 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:12:14:45,3448", "6:34:14:45" };       string[] cultureNames = { "hr-HR", "en-US"};       foreach (string cultureName in cultureNames)       {          Thread.CurrentThread.CurrentCulture = new CultureInfo(cultureName);          foreach (string value in values)          {             try {                TimeSpan ts = TimeSpan.Parse(value);                Console.WriteLine("{0} --> {1}", value, ts.ToString("c"));             }             catch (FormatException) {                Console.WriteLine("{0}: Bad Format", value);             }                catch (OverflowException) {                Console.WriteLine("{0}: Overflow", value);             }          }                                      }    } }