Partager via


DateTime.ParseExact Method (String, String, IFormatProvider, DateTimeStyles)

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Converts the specified string representation of a date and time to its DateTime equivalent using the specified format, culture-specific format information, and style. The format of the string representation must match the specified format exactly or an exception is thrown.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

Syntax

'Declaration
Public Shared Function ParseExact ( _
    s As String, _
    format As String, _
    provider As IFormatProvider, _
    style As DateTimeStyles _
) As DateTime
public static DateTime ParseExact(
    string s,
    string format,
    IFormatProvider provider,
    DateTimeStyles style
)

Parameters

  • s
    Type: System.String
    A string that contains a date and time to convert.
  • format
    Type: System.String
    A format specifier that defines the required format of s.
  • provider
    Type: System.IFormatProvider
    An object that supplies culture-specific formatting information about s.
  • style
    Type: System.Globalization.DateTimeStyles
    A bitwise combination of the enumeration values that provides additional information about s, about style elements that may be present in s, or about the conversion from s to a DateTime value. A typical value to specify is None.

Return Value

Type: System.DateTime
An object that is equivalent to the date and time contained in the s parameter, as specified by the format, provider, and style parameters.

Exceptions

Exception Condition
ArgumentNullException

s or format is nulla null reference (Nothing in Visual Basic).

FormatException

s or format is an empty string.

-or-

s does not contain a date and time that corresponds to the pattern specified in format.

ArgumentException

style contains an invalid combination of DateTimeStyles values. For example, both AssumeLocal and AssumeUniversal.

Remarks

The DateTime.ParseExact(String, String, IFormatProvider, DateTimeStyles) method parses the string representation of a date, which must be in a format defined by the format parameter. It also requires that the date and time elements in s appear in the order specified by format. If s does not match the pattern of the format parameter, with any variations defined by the style parameter, the method throws a FormatException. In contrast, the DateTime.Parse(String, IFormatProvider, DateTimeStyles) method parses the string representation of a date in any one of the patterns supported by the format provider's DateTimeFormatInfo object. The DateTime.Parse(String, IFormatProvider, DateTimeStyles) method also allows the date and time elements in s to appear in any order.

If the s parameter contains only a time and no date, the current date is used unless the style parameter includes the DateTimeStyles.NoCurrentDateDefault flag, in which case the default date (DateTime.Date.MinValue) is used. If the s parameter contains only a date and no time, midnight (00:00:00) is used. The style parameter also determines whether the s parameter can contain leading, inner, or trailing white space characters.

If s contains no time zone information, the Kind property of the returned DateTime object is DateTimeKind.Unspecified. This behavior can be changed by using the DateTimeStyles.AssumeLocal flag, which returns a DateTime value whose Kind property is DateTimeKind.Local, or by using the DateTimeStyles.AssumeUniversal and DateTimeStyles.AdjustToUniversal flags, which returns a DateTime value whose Kind property is DateTimeKind.Utc. If s contains time zone information, the time is converted to local time, if necessary, and the Kind property of the returned DateTime object is set to DateTimeKind.Local. This behavior can be changed by using the DateTimeStyles.RoundtripKind flag to not convert Coordinated Universal Time (UTC) to a local time and to set the Kind property to DateTimeKind.Utc.

The format parameter defines the required pattern of the s parameter. It can consist of either one or more custom format specifiers from the Custom Date and Time Format Strings table, or a single standard format specifier, which identifies a predefined pattern, from the Standard Date and Time Format Strings table.

If you do not use date or time separators in a custom format pattern, use the invariant culture for the provider parameter and the widest form of each custom format specifier. For example, if you want to specify hours in the pattern, specify the wider form, "HH", instead of the narrower form, "H".

NoteNote:

Rather than requiring that s conform to a single format for the parse operation to succeed, you can call the DateTime.ParseExact(String, array<String[], IFormatProvider, DateTimeStyles) method and specify multiple permitted formats. This makes the parse operation more likely to succeed.

The styles parameter includes one or more members of the DateTimeStyles enumeration that determine whether and where white space not defined by format can appear in s and that control the precise behavior of the parse operation. The following table describes how each member of the DateTimeStyles enumeration affects the operation of the ParseExact(String, String, IFormatProvider, DateTimeStyles) method.

DateTimeStyles member

Description

AdjustToUniversal

Parses s and, if necessary, converts it to UTC. If s includes a time zone offset, or if s contains no time zone information but styles includes the DateTimeStyles.AssumeLocal flag, the method parses the string, calls ToUniversalTime to convert the returned DateTime value to UTC, and sets the Kind property to DateTimeKind.Utc. If s indicates that it represents UTC, or if s does not contain time zone information but styles includes the DateTimeStyles.AssumeUniversal flag, the method parses the string, performs no time zone conversion on the returned DateTime value, and sets the Kind property to DateTimeKind.Utc. In all other cases, the flag has no effect.

AllowInnerWhite

Specifies that white space not defined by format can appear between any individual date or time element.

AllowLeadingWhite

Specifies that white space not defined by format can appear at the beginning of s.

AllowTrailingWhite

Specifies that white space not defined by format can appear at the end of s.

AllowWhiteSpaces

Specifies that s may contain leading, inner, and trailing white spaces not defined by format.

AssumeLocal

Specifies that if s lacks any time zone information, it is assumed to represent a local time. Unless the DateTimeStyles.AdjustToUniversal flag is present, the Kind property of the returned DateTime value is set to DateTimeKind.Local.

AssumeUniversal

Specifies that if s lacks any time zone information, it is assumed to represent UTC. Unless the DateTimeStyles.AdjustToUniversal flag is present, the method converts the returned DateTime value from UTC to local time and sets its Kind property to DateTimeKind.Local.

NoCurrentDateDefault

If s contains time without date information, the date of the return value is set to DateTime.MinValue.Date.

None

The s parameter is parsed using default values. No white space other than that present in format is allowed. If s lacks a date component, the date of the returned DateTime value is set to 1/1/0001. If s contains no time zone information, the Kind property of the returned DateTime object is set to DateTimeKind.Unspecified. If time zone information is present in s, the time is converted to local time and the Kind property of the returned DateTime object is set to DateTimeKind.Local.

RoundtripKind

For strings that contain time zone information, tries to prevent the conversion to a DateTime value date and time with its Kind property set to DateTimeKind.Local. This flag primarily prevents the conversion of UTC times to local times.

The particular date and time symbols and strings (such as the names of the days of the week in a particular language) used in s are defined by the provider parameter, as is the precise format of s if format is a standard format specifier string. The provider parameter can be any of the following:

If provider is nulla null reference (Nothing in Visual Basic), the CultureInfo object that corresponds to the current culture is used.

Platform Notes

Silverlight for Windows Phone Silverlight for Windows Phone

 The ParseExact method accepts an incorrect time instead of throwing FormatException.

Examples

The following example demonstrates the ParseExact(String, String, IFormatProvider) method. Note that the string " 5/01/2009 8:30 AM" cannot be parsed successfully when the styles parameter equals DateTimeStyles.None because leading spaces are not allowed by format. Additionally, the string "5/01/2009 09:00" cannot be parsed successfully with a format of "MM/dd/yyyy hh:mm" because the date string does not precede the month number with a leading zero, as format requires.

Dim enUS As New CultureInfo("en-US")
Dim dateString As String
Dim dateValue As Date

' Parse date with no style flags.
dateString = " 5/01/2009 8:30 AM"
Try
   dateValue = Date.ParseExact(dateString, "g", enUS, DateTimeStyles.None)
   outputBlock.Text += String.Format("Converted '{0}' to {1} ({2}).", dateString, dateValue, _
                     dateValue.Kind) & vbCrLf
Catch e As FormatException
   outputBlock.Text += String.Format("'{0}' is not in an acceptable format.", dateString) & vbCrLf
End Try
' Allow a leading space in the date string.
Try
   dateValue = Date.ParseExact(dateString, "g", enUS, DateTimeStyles.AllowLeadingWhite)
   outputBlock.Text += String.Format("Converted '{0}' to {1} ({2}).", dateString, dateValue, _
                     dateValue.Kind) & vbCrLf
Catch e As FormatException
   outputBlock.Text += String.Format("'{0}' is not in an acceptable format.", dateString) & vbCrLf
End Try

' Use custom formats with M and MM.
dateString = "5/01/2009 09:00"
Try
   dateValue = Date.ParseExact(dateString, "M/dd/yyyy hh:mm", enUS, DateTimeStyles.None)
   outputBlock.Text += String.Format("Converted '{0}' to {1} ({2}).", dateString, dateValue, _
                     dateValue.Kind) & vbCrLf
Catch e As FormatException
   outputBlock.Text += String.Format("'{0}' is not in an acceptable format.", dateString) & vbCrLf
End Try
' Allow a leading space in the date string.
Try
   dateValue = Date.ParseExact(dateString, "MM/dd/yyyy hh:mm", enUS, DateTimeStyles.None)
   outputBlock.Text += String.Format("Converted '{0}' to {1} ({2}).", dateString, dateValue, _
                     dateValue.Kind) & vbCrLf
Catch e As FormatException
   outputBlock.Text += String.Format("'{0}' is not in an acceptable format.", dateString) & vbCrLf
End Try

' Parse a string with time zone information.
dateString = "05/01/2009 01:30:42 PM -05:00"
Try
   dateValue = Date.ParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS, DateTimeStyles.None)
   outputBlock.Text += String.Format("Converted '{0}' to {1} ({2}).", dateString, dateValue, _
                     dateValue.Kind) & vbCrLf
Catch e As FormatException
   outputBlock.Text += String.Format("'{0}' is not in an acceptable format.", dateString) & vbCrLf
End Try
' Allow a leading space in the date string.
Try
   dateValue = Date.ParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS, _
                               DateTimeStyles.AdjustToUniversal)
   outputBlock.Text += String.Format("Converted '{0}' to {1} ({2}).", dateString, dateValue, _
                     dateValue.Kind) & vbCrLf
Catch e As FormatException
   outputBlock.Text += String.Format("'{0}' is not in an acceptable format.", dateString) & vbCrLf
End Try

' Parse a string represengting UTC.
dateString = "2008-06-11T16:11:20.0904778Z"
Try
   dateValue = Date.ParseExact(dateString, "o", CultureInfo.InvariantCulture, _
                               DateTimeStyles.None)
   outputBlock.Text += String.Format("Converted '{0}' to {1} ({2}).", dateString, dateValue, _
                     dateValue.Kind) & vbCrLf
Catch e As FormatException
   outputBlock.Text += String.Format("'{0}' is not in an acceptable format.", dateString) & vbCrLf
End Try
Try
   dateValue = Date.ParseExact(dateString, "o", CultureInfo.InvariantCulture, _
                               DateTimeStyles.RoundtripKind)
   outputBlock.Text += String.Format("Converted '{0}' to {1} ({2}).", dateString, dateValue, _
                     dateValue.Kind) & vbCrLf
Catch e As FormatException
   outputBlock.Text += String.Format("'{0}' is not in an acceptable format.", dateString) & vbCrLf
End Try
' The example displays the following output:
'    ' 5/01/2009 8:30 AM' is not in an acceptable format.
'    Converted ' 5/01/2009 8:30 AM' to 5/1/2009 8:30:00 AM (Unspecified).
'    Converted '5/01/2009 09:00' to 5/1/2009 9:00:00 AM (Unspecified).
'    '5/01/2009 09:00' is not in an acceptable format.
'    Converted '05/01/2009 01:30:42 PM -05:00' to 5/1/2009 11:30:42 AM (Local).
'    Converted '05/01/2009 01:30:42 PM -05:00' to 5/1/2009 6:30:42 PM (Utc).
'    Converted '2008-06-11T16:11:20.0904778Z' to 6/11/2008 9:11:20 AM (Local).
'    Converted '2008-06-11T16:11:20.0904778Z' to 6/11/2008 4:11:20 PM (Utc).
CultureInfo enUS = new CultureInfo("en-US");
string dateString;
DateTime dateValue;

// Parse date with no style flags.
dateString = " 5/01/2009 8:30 AM";
try
{
   dateValue = DateTime.ParseExact(dateString, "g", enUS, DateTimeStyles.None);
   outputBlock.Text += String.Format("Converted '{0}' to {1} ({2}).\n", dateString, dateValue,
                     dateValue.Kind);
}
catch (FormatException)
{
   outputBlock.Text += String.Format("'{0}' is not in an acceptable format.\n", dateString);
}
// Allow a leading space in the date string.
try
{
   dateValue = DateTime.ParseExact(dateString, "g", enUS, DateTimeStyles.AllowLeadingWhite);
   outputBlock.Text += String.Format("Converted '{0}' to {1} ({2}).\n", dateString, dateValue,
                     dateValue.Kind);
}
catch (FormatException)
{
   outputBlock.Text += String.Format("'{0}' is not in an acceptable format.\n", dateString);
}

// Use custom formats with M and MM.
dateString = "5/01/2009 09:00";
try
{
   dateValue = DateTime.ParseExact(dateString, "M/dd/yyyy hh:mm", enUS, DateTimeStyles.None);
   outputBlock.Text += String.Format("Converted '{0}' to {1} ({2}).\n", dateString, dateValue,
                     dateValue.Kind);
}
catch (FormatException)
{
   outputBlock.Text += String.Format("'{0}' is not in an acceptable format.\n", dateString);
}
// Allow a leading space in the date string.
try
{
   dateValue = DateTime.ParseExact(dateString, "MM/dd/yyyy hh:mm", enUS, DateTimeStyles.None);
   outputBlock.Text += String.Format("Converted '{0}' to {1} ({2}).\n", dateString, dateValue,
                     dateValue.Kind);
}
catch (FormatException)
{
   outputBlock.Text += String.Format("'{0}' is not in an acceptable format.\n", dateString);
}

// Parse a string with time zone information.
dateString = "05/01/2009 01:30:42 PM -05:00";
try
{
   dateValue = DateTime.ParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS, DateTimeStyles.None);
   outputBlock.Text += String.Format("Converted '{0}' to {1} ({2}).\n", dateString, dateValue,
                     dateValue.Kind);
}
catch (FormatException)
{
   outputBlock.Text += String.Format("'{0}' is not in an acceptable format.\n", dateString);
}
// Allow a leading space in the date string.
try
{
   dateValue = DateTime.ParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS,
                               DateTimeStyles.AdjustToUniversal);
   outputBlock.Text += String.Format("Converted '{0}' to {1} ({2}).\n", dateString, dateValue,
                     dateValue.Kind);
}
catch (FormatException)
{
   outputBlock.Text += String.Format("'{0}' is not in an acceptable format.\n", dateString);
}

// Parse a string represengting UTC.
dateString = "2008-06-11T16:11:20.0904778Z";
try
{
   dateValue = DateTime.ParseExact(dateString, "o", CultureInfo.InvariantCulture,
                               DateTimeStyles.None);
   outputBlock.Text += String.Format("Converted '{0}' to {1} ({2}).\n", dateString, dateValue,
                     dateValue.Kind);
}
catch (FormatException)
{
   outputBlock.Text += String.Format("'{0}' is not in an acceptable format.\n", dateString);
}
try
{
   dateValue = DateTime.ParseExact(dateString, "o", CultureInfo.InvariantCulture,
                               DateTimeStyles.RoundtripKind);
   outputBlock.Text += String.Format("Converted '{0}' to {1} ({2}).\n", dateString, dateValue,
                     dateValue.Kind);
}
catch (FormatException)
{
   outputBlock.Text += String.Format("'{0}' is not in an acceptable format.\n", dateString);
}
// The example displays the following output:
//    ' 5/01/2009 8:30 AM' is not in an acceptable format.
//    Converted ' 5/01/2009 8:30 AM' to 5/1/2009 8:30:00 AM (Unspecified).
//    Converted '5/01/2009 09:00' to 5/1/2009 9:00:00 AM (Unspecified).
//    '5/01/2009 09:00' is not in an acceptable format.
//    Converted '05/01/2009 01:30:42 PM -05:00' to 5/1/2009 11:30:42 AM (Local).
//    Converted '05/01/2009 01:30:42 PM -05:00' to 5/1/2009 6:30:42 PM (Utc).
//    Converted '2008-06-11T16:11:20.0904778Z' to 6/11/2008 9:11:20 AM (Local).
//    Converted '2008-06-11T16:11:20.0904778Z' to 6/11/2008 4:11:20 PM (Utc).

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.