C# DateTime ParseExact(String, String, IFormatProvider)
Description
DateTime ParseExact(String, String, IFormatProvider)
converts
the specified string representation of a date and time to its DateTime equivalent
using the specified format and culture-specific format information. The
format of the string representation must match the specified format exactly.
Syntax
DateTime.ParseExact(String, String, IFormatProvider)
has the following syntax.
public static DateTime ParseExact(
string s,// ww w.j av a 2 s.com
string format,
IFormatProvider provider
)
Parameters
DateTime.ParseExact(String, String, IFormatProvider)
has the following parameters.
s
- A string that contains a date and time to convert.format
- A format specifier that defines the required format of s. For more information, see the Remarks section.provider
- An object that supplies culture-specific format information about s.
Returns
DateTime.ParseExact(String, String, IFormatProvider)
method returns An object that is equivalent to the date and time contained in s, as specified
by format and provider.
Example
The following example demonstrates the ParseExact method.
// ww w.j a v a2 s . c o m
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
string dateString, format;
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;
// Parse date-only value with invariant culture.
dateString = "06/15/2008";
format = "d";
try {
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
}
dateString = "6/15/2008";
try {
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
}
// Parse date and time with custom specifier.
dateString = "Sun 15 Jun 2008 8:30 AM -06:00";
format = "ddd dd MMM yyyy h:mm tt zzz";
try {
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
}
dateString = "Sun 15 Jun 2008 8:30 AM -06";
try {
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
}
dateString = "15/06/2008 08:30";
format = "g";
provider = new CultureInfo("fr-FR");
try {
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
}
}
}
The code above generates the following result.