Parse string to TimeSpan using formats, culture, and styles in CSharp

Description

The following code shows how to parse string to TimeSpan using formats, culture, and styles.

Example


using System;/*from  ww  w . j ava  2s .c o  m*/
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("de-DE");

      foreach (string input in inputs) {
         interval = TimeSpan.ParseExact(input, formats, culture,
                                           TimeSpanStyles.AssumeNegative);
         Console.WriteLine("{0} --> {1:c}", input, interval);
      }
   }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Data Types »




C# Data Types
Bool
Byte
Char
Decimal
Double
Float
Integer
Long
Short
String
C# Array
Array Example
Byte Array
C# Standard Data Type Format
BigInteger
Complex
Currency
DateTime
DateTimeOffset
DateTime Format Parse Convert
TimeSpan
TimeZone
Enum
Null
tuple
var