C# TimeSpan Parse(String)

Description

TimeSpan Parse(String) converts the string representation of a time interval to its TimeSpan equivalent.

Syntax

TimeSpan.Parse(String) has the following syntax.


public static TimeSpan Parse(
  string s
)

Parameters

TimeSpan.Parse(String) has the following parameters.

  • s - A string that specifies the time interval to convert.

Returns

TimeSpan.Parse(String) method returns A time interval that corresponds to s.

Example

The following example illustrates how to use TimeSpan.Parse(String) method.


using System.Threading;
using System;/* ww w.  j  ava 2  s .  co  m*/
using System.Globalization;


public class MainClass
{
    public static void Main(String[] argv){  
        
    string[] values = { "000000006", "12.12:12:12.12345678" };
    foreach (string value in values)
    {
       try {
          TimeSpan interval = TimeSpan.Parse(value);
          Console.WriteLine("{0} --> {1}", value, interval);
       }   
       catch (FormatException) {
          Console.WriteLine("{0}: Bad Format", value);
       }   
       catch (OverflowException) {
          Console.WriteLine("{0}: Overflow", value);
       }
    }
     values = new string[] { "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"};

      // Change the current culture. 
      foreach (string cultureName in cultureNames)
      {
         Thread.CurrentThread.CurrentCulture = new CultureInfo(cultureName);
         Console.WriteLine("Current Culture: {0}", 
                           Thread.CurrentThread.CurrentCulture.Name);
         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);
            }
         } 
         Console.WriteLine();                                
      }
  }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version