C# TimeSpan TryParseExact(String, String, IFormatProvider, TimeSpan)
Description
TimeSpan TryParseExact(String, String, IFormatProvider,
TimeSpan)
converts the string representation of a time interval
to its TimeSpan equivalent by using the specified format and culture-specific
format information, 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, TimeSpan)
has the following syntax.
public static bool TryParseExact(
string input,//from w w w .j av a 2 s. com
string format,
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.format
- A standard or custom format string that defines the required format of input.formatProvider
- An object that supplies 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 uses the TryParseExact(String, String, IFormatProvider, TimeSpanStyles, TimeSpan) method to parse several string representations of time intervals using various format strings and cultures.
/*w w w. java 2 s. c o m*/
using System;
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;
if (TimeSpan.TryParseExact(intervalString, format, culture, out interval))
Console.WriteLine("'{0}' --> {1}", intervalString, interval);
else
Console.WriteLine("Unable to parse {0}", intervalString);
}
}
The code above generates the following result.