Parse string to TimeSpan

In this chapter you will learn:

  1. Use the Parse() method to convert strings to TimeSpan instances: 8:10:30
  2. Use the Parse() method to convert strings to TimeSpan instances: 1.8:10:30.1234567
  3. Converts string to TimeSpan by using the specified format and culture-specific format information

Parse string

using System;//j  a v a 2s .  co  m

class MainClas
{
  public static void Main()
  {
    
    TimeSpan myTimeSpan11 = TimeSpan.Parse("8:10:30");
    Console.WriteLine("TimeSpan.Parse(\"8:10:30\") = " + myTimeSpan11);
  }
}

The code above generates the following result.

Parse string with milliseconds

using System;// ja  v  a  2 s . c  o m

class MainClas
{
  public static void Main()
  {
    
    TimeSpan myTimeSpan12 = TimeSpan.Parse("1.8:10:30.1234567");
    Console.WriteLine("TimeSpan.Parse(\"1.8:10:30.1234567\") = " + myTimeSpan12);
  }
}

The code above generates the following result.

Parse string with culture information

using System;// jav a2 s  .  c o  m
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string intervalString, format;
      TimeSpan interval;
      CultureInfo culture;

      // Parse hour:minute value with "g" specifier current culture.
      intervalString = "17:14";
      format = "g";
      culture = CultureInfo.CurrentCulture;
      try {
         interval = TimeSpan.ParseExact(intervalString, format, culture);
         Console.WriteLine("'{0}' --> {1}", intervalString, interval);
      }
      catch (FormatException) {
         Console.WriteLine("'{0}': Bad Format for '{1}'", 
                           intervalString, format);
      }                     
      catch (OverflowException) {
         Console.WriteLine("'{0}': Overflow", intervalString);
      }      

   }
}

Next chapter...

What you will learn in the next chapter:

  1. Default output of ToString() method
Home » C# Tutorial » Date, Time, TimeZone
Compare DateTimeOffset
DateTimeOffset creation
Date time Value from DateTimeOffset
Compare DateTime value
DateTime constant value
DateTime constructor
DateTime properties
Create TimeSpan From
TimeSpan
TimeSpan add and subtract
DateTime and TimeSpan
Compare TimeSpan
TimeSpan constant
TimeSpan Constructor
TimeSpan Duration
TimeSpan format
Negate a TimeSpan
TimeSpan operators
Parse string to TimeSpan
TimeSpan to string
TimeSpan total properties
TimeSpan propeties
Daylight saving
Time zone ID
UTC offset with TimeZone
TimeZone converting
TimeZone creation