C# TimeSpan TryParseExact(String, String, IFormatProvider, TimeSpanStyles, TimeSpan)

Description

TimeSpan TryParseExact(String, String, IFormatProvider, TimeSpanStyles, TimeSpan) converts the string representation of a time interval to its TimeSpan equivalent by using the specified format, culture-specific format information, and styles, and returns a value that indicates whether the conversion succeeded. The format of the string representation must match the specified format exactly.

Syntax

TimeSpan.TryParseExact(String, String, IFormatProvider, TimeSpanStyles, TimeSpan) has the following syntax.


public static bool TryParseExact(
  string input,// w ww  .j  a  v a 2 s . c o  m
  string format,
  IFormatProvider formatProvider,
  TimeSpanStyles styles,
  out TimeSpan result
)

Parameters

TimeSpan.TryParseExact(String, String, IFormatProvider, TimeSpanStyles, TimeSpan) has the following parameters.

  • input - A string that specifies the time interval to convert.
  • format - A standard or custom format string that defines the required format of input.
  • formatProvider - An object that provides culture-specific formatting information.
  • styles - One or more enumeration values that indicate the style of input.
  • result - When this method returns, contains an object that represents the time interval specified by input, or TimeSpan.Zero if the conversion failed. This parameter is passed uninitialized.

Returns

TimeSpan.TryParseExact(String, String, IFormatProvider, TimeSpanStyles, TimeSpan) method returns true if input was converted successfully; otherwise, false.

Example

The following example uses the ParseExact(String, String, IFormatProvider) method to parse several string representations of time intervals using various format strings and cultures.


using System;//from ww  w  . j  a  v  a2s .  c o  m
using System.Globalization;

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

      // Parse hour:minute value with custom format specifier.
      intervalString = "17:14";
      format = "h\\:mm";
      culture = CultureInfo.CurrentCulture;
      if (TimeSpan.TryParseExact(intervalString, format, 
                                 culture, TimeSpanStyles.AssumeNegative, out interval))
         Console.WriteLine("'{0}' ({1}) --> {2}", intervalString, format, interval);
      else   
         Console.WriteLine("Unable to parse '{0}' using format {1}",
                           intervalString, format);

   }
}

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