Compartilhar via


DateTime.TryParse Method (String, IFormatProvider, DateTimeStyles, DateTime%)

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 culture-specific format information and formatting style, and returns a value that indicates whether the conversion succeeded.

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

Syntax

'Declaration
Public Shared Function TryParse ( _
    s As String, _
    provider As IFormatProvider, _
    styles As DateTimeStyles, _
    <OutAttribute> ByRef result As DateTime _
) As Boolean
public static bool TryParse(
    string s,
    IFormatProvider provider,
    DateTimeStyles styles,
    out DateTime result
)

Parameters

  • s
    Type: System.String
    A string that contains a date and time to convert.
  • provider
    Type: System.IFormatProvider
    An object that supplies culture-specific formatting information about s.
  • styles
    Type: System.Globalization.DateTimeStyles
    A bitwise combination of enumeration values that defines how to interpret the parsed date in relation to the current time zone or the current date. A typical value to specify is None.
  • result
    Type: System.DateTime%
    When this method returns, contains the DateTime value that is equivalent to the date and time contained in s, if the conversion succeeded, or DateTime.MinValue if the conversion failed. The conversion fails if the s parameter is nulla null reference (Nothing in Visual Basic), is an empty string (""), or does not contain a valid string representation of a date and time. This parameter is passed uninitialized.

Return Value

Type: System.Boolean
true if the s parameter was converted successfully; otherwise, false.

Exceptions

Exception Condition
ArgumentException

styles is not a valid DateTimeStyles value.

-or-

styles contains an invalid combination of DateTimeStyles values (for example, both AssumeLocal and AssumeUniversal).

NotSupportedException

provider is a neutral culture and cannot be used in a parsing operation.

Remarks

The DateTime.TryParse(String, IFormatProvider, DateTimeStyles, DateTime%) method parses a string that can contain date, time, and time zone information. It is similar to the DateTime.Parse(String, IFormatProvider, DateTimeStyles) method, except that the DateTime.TryParse(String, DateTime%) method does not throw an exception if the conversion fails.

The s parameter must contain the representation of a date and time in one of the formats recognized by the DateTimeFormatInfo object retrieved from the provider parameter. This method attempts to ignore unrecognized data and parse s completely. If s contains a time but no date, the method by default substitutes the current date or, if styles includes the NoCurrentDateDefault flag, it substitutes DateTime.Date.MinValue. If s contains a date but no time, 12:00 midnight is used as the default time. If a date is present but its year component consists of only two digits, it is converted to a year in the provider parameter's current calendar based on the value of the Calendar.TwoDigitYearMax property. Any leading, inner, or trailing white space characters in s are ignored.

Specific valid formats for date and time elements, as well as the names and symbols used in dates and times, are defined by the provider parameter, which can be any of the following:

If provider is nulla null reference (Nothing in Visual Basic), the current culture is used.

The styles parameter defines the precise interpretation of the parsed string and how the parse operation should handle it. It can be one or more members of the DateTimeStyles enumeration, as described in the following table.

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

Although valid, this value is ignored. Inner white space is permitted in the date and time elements of s.

AllowLeadingWhite

Although valid, this value is ignored. Leading white space is permitted in the date and time elements of s.

AllowTrailingWhite

Although valid, this value is ignored. Trailing white space is permitted in the date and time elements of s.

AllowWhiteSpaces

Specifies that s may contain leading, inner, and trailing white spaces. This is the default behavior. It cannot be overridden by supplying a more restrictive DateTimeStyles enumeration value such as DateTimeStyles.None.

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.

None

Although valid, this value is ignored.

RoundtripKind

For strings that contain time zone information, tries to prevent the conversion of a date and time string to a DateTime value with its Kind property set to DateTimeKind.Local. Typically, such a string is created by calling the DateTime.ToString(String) method using either the o, r, or u standard format specifiers.

If s contains no time zone information, the DateTime.TryParse(String, IFormatProvider, DateTimeStyles, DateTime%) method returns a DateTime value whose Kind property is DateTimeKind.Unspecified unless a styles flag indicates otherwise. If s includes time zone or time zone offset information, the DateTime.TryParse(String, IFormatProvider, DateTimeStyles, DateTime%) method performs any necessary time conversion and returns one of the following:

This behavior can be overridden by using the DateTimeStyles.RoundtripKind flag.

Parsing Custom Cultures

If you parse a date and time string generated for a custom culture, use the TryParseExact method instead of the TryParse method to improve the probability that the parse operation will succeed. A custom culture date and time string can be complicated and difficult to parse. The TryParse method attempts to parse a string with several implicit parse patterns, all of which might fail. In contrast, the TryParseExact method requires you to explicitly designate one or more exact parse patterns that are likely to succeed.

Examples

The following example illustrates the DateTime.TryParse(String, IFormatProvider, DateTimeStyles, DateTime%) method.

Dim dateString As String
Dim culture As CultureInfo
Dim styles As DateTimeStyles
Dim dateResult As DateTime

' Parse a date and time with no styles.
dateString = "03/01/2009 10:00 AM"
culture = New CultureInfo("en-US")
styles = DateTimeStyles.None
If DateTime.TryParse(dateString, culture, styles, dateResult) Then
   outputBlock.Text &= String.Format("{0} converted to {1} {2}.", _
                     dateString, dateResult, dateResult.Kind) & vbCrLf
Else
   outputBlock.Text &= String.Format("Unable to convert {0} to a date and time.", dateString) & vbCrLf
End If

' Parse the same date and time with the AssumeLocal style.
styles = DateTimeStyles.AssumeLocal
If DateTime.TryParse(dateString, culture, styles, dateResult) Then
   outputBlock.Text &= String.Format("{0} converted to {1} {2}.", _
                     dateString, dateResult, dateResult.Kind) & vbCrLf
Else
   outputBlock.Text &= String.Format("Unable to convert {0} to a date and time.", dateString) & vbCrLf
End If

' Parse a date and time that is assumed to be local.
' This time is five hours behind UTC. The local system's time zone is 
' eight hours behind UTC.
dateString = "2009/03/01T10:00:00-5:00"
styles = DateTimeStyles.AssumeLocal
If DateTime.TryParse(dateString, culture, styles, dateResult) Then
   outputBlock.Text &= String.Format("{0} converted to {1} {2}.", _
                     dateString, dateResult, dateResult.Kind) & vbCrLf
Else
   outputBlock.Text &= String.Format("Unable to convert {0} to a date and time.", dateString) & vbCrLf
End If

' Attempt to convert a string in improper ISO 8601 format.
dateString = "03/01/2009T10:00:00-5:00"
If DateTime.TryParse(dateString, culture, styles, dateResult) Then
   outputBlock.Text &= String.Format("{0} converted to {1} {2}.", _
                     dateString, dateResult, dateResult.Kind) & vbCrLf
Else
   outputBlock.Text &= String.Format("Unable to convert {0} to a date and time.", dateString) & vbCrLf
End If

' Assume a date and time string formatted for the fr-FR culture is the local 
' time and convert it to UTC.
dateString = "2008-03-01 10:00"
culture = New CultureInfo("fr-FR")
styles = DateTimeStyles.AdjustToUniversal Or DateTimeStyles.AssumeLocal
If DateTime.TryParse(dateString, culture, styles, dateResult) Then
   outputBlock.Text &= String.Format("{0} converted to {1} {2}.", _
                     dateString, dateResult, dateResult.Kind) & vbCrLf
Else
   outputBlock.Text &= String.Format("Unable to convert {0} to a date and time.", dateString) & vbCrLf
End If
'
' The example displays the following output:
'       03/01/2009 10:00 AM converted to 3/1/2009 10:00:00 AM Unspecified.
'       03/01/2009 10:00 AM converted to 3/1/2009 10:00:00 AM Local.
'       2009/03/01T10:00:00-5:00 converted to 3/1/2009 7:00:00 AM Local.
'       Unable to convert 03/01/2009T10:00:00-5:00 to a date and time.
'       2008-03-01 10:00 converted to 3/1/2008 6:00:00 PM Utc.
string dateString;
CultureInfo culture;
DateTimeStyles styles;
DateTime dateResult;

// Parse a date and time with no styles.
dateString = "03/01/2009 10:00 AM";
culture = new CultureInfo("en-US");
styles = DateTimeStyles.None;
if (DateTime.TryParse(dateString, culture, styles, out dateResult))
   outputBlock.Text += String.Format("{0} converted to {1} {2}.",
                     dateString, dateResult, dateResult.Kind) + "\n";
else
   outputBlock.Text += String.Format("Unable to convert {0} to a date and time.",
                     dateString) + "\n";

// Parse the same date and time with the AssumeLocal style.
styles = DateTimeStyles.AssumeLocal;
if (DateTime.TryParse(dateString, culture, styles, out dateResult))
   outputBlock.Text += String.Format("{0} converted to {1} {2}.",
                     dateString, dateResult, dateResult.Kind) + "\n";
else
   outputBlock.Text += String.Format("Unable to convert {0} to a date and time.", dateString) + "\n";

// Parse a date and time that is assumed to be local.
// This time is five hours behind UTC. The local system's time zone is 
// eight hours behind UTC.
dateString = "2009/03/01T10:00:00-5:00";
styles = DateTimeStyles.AssumeLocal;
if (DateTime.TryParse(dateString, culture, styles, out dateResult))
   outputBlock.Text += String.Format("{0} converted to {1} {2}.",
                     dateString, dateResult, dateResult.Kind) + "\n";
else
   outputBlock.Text += String.Format("Unable to convert {0} to a date and time.", dateString) + "\n";

// Attempt to convert a string in improper ISO 8601 format.
dateString = "03/01/2009T10:00:00-5:00";
if (DateTime.TryParse(dateString, culture, styles, out dateResult))
   outputBlock.Text += String.Format("{0} converted to {1} {2}.",
                     dateString, dateResult, dateResult.Kind) + "\n";
else
   outputBlock.Text += String.Format("Unable to convert {0} to a date and time.", dateString) + "\n";

// Assume a date and time string formatted for the fr-FR culture is the local 
// time and convert it to UTC.
dateString = "2008-03-01 10:00";
culture = new CultureInfo("fr-FR");
styles = DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeLocal;
if (DateTime.TryParse(dateString, culture, styles, out dateResult))
   outputBlock.Text += String.Format("{0} converted to {1} {2}.",
                     dateString, dateResult, dateResult.Kind) + "\n";
else
   outputBlock.Text += String.Format("Unable to convert {0} to a date and time.", dateString) + "\n";

// The example displays the following output:
//       03/01/2009 10:00 AM converted to 3/1/2009 10:00:00 AM Unspecified.
//       03/01/2009 10:00 AM converted to 3/1/2009 10:00:00 AM Local.
//       2009/03/01T10:00:00-5:00 converted to 3/1/2009 7:00:00 AM Local.
//       Unable to convert 03/01/2009T10:00:00-5:00 to a date and time.
//       2008-03-01 10:00 converted to 3/1/2008 6:00:00 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.