Parse strings to TimeSpan : Time Span Parse « Date Time « C# / C Sharp






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);
            }
         }                               
      }
   }
}

   
    
  








Related examples in the same category

1.Parse string to TimeSpan
2.Parse string to TimeSpan: "18:31.05"
3.Parse string to TimeSpan: "12.035"
4.TimeSpan.Parse("0:0:3.669")
5.Parse hour:minute value with "g" specifier current culture.
6.Parse hour:minute:second value with "G" specifier.
7.Parse hours:minute.second value with "G" specifier and current (en-US) culture.
8.Parse days:hours:minute.second value with "G" specifier and current (en-US) culture.
9.Parse days:hours:minute.second value with "G" specifier and fr-FR culture.
10.Parse a single number using the "c" standard format string.
11.Parse a single number using the "%h" custom format string.
12.Is Date valid
13.Parse Rfc 2822 Date