C# TimeSpan TryParseExact(String, String[], IFormatProvider, TimeSpan) Array

Description

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

Syntax

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


public static bool TryParseExact(
  string input,//from w w w  . ja  v a2 s. c  o  m
  string[] formats,
  IFormatProvider formatProvider,
  out TimeSpan result
)

Parameters

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

  • input - A string that specifies the time interval to convert.
  • formats - A array of standard or custom format strings that define the acceptable formats of input.
  • formatProvider - An object that provides culture-specific formatting information.
  • 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, TimeSpan) method returns true if input was converted successfully; otherwise, false.

Example

The following example calls the TryParseExact(String, String[], IFormatProvider, TimeSpan) method to convert each element of a string array to a TimeSpan value.


using System;/*from w w w .  j  a v  a 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 = { "g", "G", "%h"};
      TimeSpan interval;
      CultureInfo culture = new CultureInfo("fr-FR");

      foreach (string input in inputs) {
         if(TimeSpan.TryParseExact(input, formats, culture, out interval))
            Console.WriteLine("{0} --> {1:c}", input, interval);
         else
            Console.WriteLine("Unable to parse {0}", input);   
      }
   }
}

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