DateTime.Parse Method (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 culture-specific format information and formatting style.

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

Syntax

'Declaration
Public Shared Function Parse ( _
    s As String, _
    provider As IFormatProvider, _
    styles As DateTimeStyles _
) As DateTime
public static DateTime Parse(
    string s,
    IFormatProvider provider,
    DateTimeStyles styles
)

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 the enumeration values that indicates the style elements that can be present in s for the parse operation to succeed, and 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.

Return Value

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

Exceptions

Exception Condition
ArgumentNullException

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

FormatException

s does not contain a valid string representation of a date and time.

ArgumentException

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

Remarks

This method parses a string with two elements that can appear in any order and are delimited by white space. These two elements are shown in the following table.

Date and time element

Example (en-US culture)

<Date>

"2/10/2009"

<Time>

"1:02:03 PM"

Either <Date> or <Time> but not both elements can be absent from s. In addition, s can contain time zone information. If <Time> is missing, its default value is 12:00:00 AM. If <Date> is missing, its default value is the current day. If <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. However, if <Date> is missing and styles includes the NoCurrentDateDefault value, its date is assumed to be January 1, 0001. Each element can also be enclosed by leading or trailing white space and can even include inner white space (such as "6: 00: 00"). A time zone specifier (such as Z or GMT to indicate Coordinated Universal Time (UTC)) can also be present. In addition, s can include a time zone offset (such as "2008-10-1T6:00:32-8:00"). In this case, the format of s must conform to the ISO 8601 standard.

The format of s is defined by the provider parameter, which can be any of the following:

Specific valid formats for date and time elements are defined by the DateTimeFormatInfo object of the culture defined by the provider parameter. If provider is nulla null reference (Nothing in Visual Basic), the CultureInfo object for the current culture is used.

The styles parameter consists of one or more members of the DateTimeStyles enumeration that define how s is to be interpreted and how the parse operation is to convert s to a date and time. The following table describes the effect of each member on the parse operation.

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 that represents a local time 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.Parse(String, IFormatProvider, DateTimeStyles) 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.Parse(String, IFormatProvider, DateTimeStyles) method performs any necessary time conversion and returns one of the following:

This behavior can be overridden by using the DateTimeStyles.RoundtripKind flag. The following example illustrates how the DateTimeStyles.RoundtripKind flag affects the parsing operation on DateTime values that are converted to strings using the o, r, or u format specifier.

   Dim formattedDates() As String = { "2008-09-15T09:30:41.7752486-07:00", _
                                      "2008-09-15T09:30:41.7752486Z", _ 
                                      "2008-09-15T09:30:41.7752486", _ 
                                      "2008-09-15T09:30:41.7752486-04:00", _
                                      "Mon, 15 Sep 2008 09:30:41 GMT" }
   For Each formattedDate As String In formattedDates
      outputBlock.Text += formattedDate + vbCrLf
      Dim roundtripDate As Date = Date.Parse(formattedDate, Nothing, _
                                          DateTimeStyles.RoundtripKind)                        
      outputBlock.Text += String.Format("   With RoundtripKind flag: {0} {1} time.", _
                        roundtripDate, roundtripDate.Kind) + vbCrlf                                          
      Dim noRoundtripDate As Date = Date.Parse(formattedDate, Nothing, _
                                          DateTimeStyles.None)
      outputBlock.Text += String.Format("   Without RoundtripKind flag: {0} {1} time.", _
                         noRoundtripDate, noRoundtripDate.Kind) + vbCrLf                                          
   Next         
' The example displays the following output:
'       2008-09-15T09:30:41.7752486-07:00
'          With RounndtripKind flag: 9/15/2008 9:30:41 AM Local time.
'          Without RoundtripKind flag: 9/15/2008 9:30:41 AM Local time.
'       2008-09-15T09:30:41.7752486Z
'          With RounndtripKind flag: 9/15/2008 9:30:41 AM Utc time.
'          Without RoundtripKind flag: 9/15/2008 2:30:41 AM Local time.
'       2008-09-15T09:30:41.7752486
'          With RounndtripKind flag: 9/15/2008 9:30:41 AM Unspecified time.
'          Without RoundtripKind flag: 9/15/2008 9:30:41 AM Unspecified time.
'       2008-09-15T09:30:41.7752486-04:00
'          With RounndtripKind flag: 9/15/2008 6:30:41 AM Local time.
'          Without RoundtripKind flag: 9/15/2008 6:30:41 AM Local time.
'       Mon, 15 Sep 2008 09:30:41 GMT
'          With RounndtripKind flag: 9/15/2008 9:30:41 AM Utc time.
'          Without RoundtripKind flag: 9/15/2008 2:30:41 AM Local time.      
   string[] formattedDates = { "2008-09-15T09:30:41.7752486-07:00", 
                               "2008-09-15T09:30:41.7752486Z",  
                               "2008-09-15T09:30:41.7752486",  
                               "2008-09-15T09:30:41.7752486-04:00", 
                               "Mon, 15 Sep 2008 09:30:41 GMT" };
   foreach (string formattedDate in formattedDates)
   {
      outputBlock.Text += formattedDate + "\n";
      DateTime roundtripDate = DateTime.Parse(formattedDate, null, 
                                              DateTimeStyles.RoundtripKind);                        
      outputBlock.Text += String.Format("   With RoundtripKind flag: {0} {1} time.\n", 
                        roundtripDate, roundtripDate.Kind);                                          
      DateTime noRoundtripDate = DateTime.Parse(formattedDate, null, 
                                                DateTimeStyles.None);
      outputBlock.Text += String.Format("   Without RoundtripKind flag: {0} {1} time.\n", 
                         noRoundtripDate, noRoundtripDate.Kind);                                          
   }         
// The example displays the following output:
//       2008-09-15T09:30:41.7752486-07:00
//          With RoundtripKind flag: 9/15/2008 9:30:41 AM Local time.
//          Without RoundtripKind flag: 9/15/2008 9:30:41 AM Local time.
//       2008-09-15T09:30:41.7752486Z
//          With RoundtripKind flag: 9/15/2008 9:30:41 AM Utc time.
//          Without RoundtripKind flag: 9/15/2008 2:30:41 AM Local time.
//       2008-09-15T09:30:41.7752486
//          With RoundtripKind flag: 9/15/2008 9:30:41 AM Unspecified time.
//          Without RoundtripKind flag: 9/15/2008 9:30:41 AM Unspecified time.
//       2008-09-15T09:30:41.7752486-04:00
//          With RoundtripKind flag: 9/15/2008 6:30:41 AM Local time.
//          Without RoundtripKind flag: 9/15/2008 6:30:41 AM Local time.
//       Mon, 15 Sep 2008 09:30:41 GMT
//          With RoundtripKind flag: 9/15/2008 9:30:41 AM Utc time.
//          Without RoundtripKind flag: 9/15/2008 2:30:41 AM Local time.      

Because the DateTime.Parse(String, IFormatProvider, DateTimeStyles) method tries to parse the string representation of a date and time using the formatting rules of the provider parameter, trying to parse a particular string across different cultures can fail. If a specific date and time format will be parsed across different locales, use one of the overloads of the ParseExact method and provide a format specifier.

Parsing Custom Cultures

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

Examples

The following example demonstrates the DateTime.Parse(String, IFormatProvider, DateTimeStyles) method.

Imports System.Globalization

Module Example
   Public Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)
      Dim dateString As String
      Dim culture As CultureInfo
      Dim styles As DateTimeStyles
      Dim result As DateTime

      ' Parse a date and time with no styles.
      dateString = "03/01/2009 10:00 AM"
      culture = CultureInfo.CreateSpecificCulture("en-US")
      styles = DateTimeStyles.None
      Try
         result = DateTime.Parse(dateString, culture, styles)
         outputBlock.Text += String.Format("{0} converted to {1} {2}.", _
                           dateString, result, result.Kind.ToString()) & vbCrLf
      Catch e As FormatException
         outputBlock.Text += String.Format("Unable to convert {0} to a date and time.", dateString) & vbCrLf
      End Try

      ' Parse the same date and time with the AssumeLocal style.
      styles = DateTimeStyles.AssumeLocal
      Try
         result = DateTime.Parse(dateString, culture, styles)
         outputBlock.Text += String.Format("{0} converted to {1} {2}.", _
                           dateString, result, result.Kind.ToString()) & vbCrLf
      Catch e As FormatException
         outputBlock.Text += String.Format("Unable to convert {0} to a date and time.", dateString) & vbCrLf
      End Try

      ' 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
      Try
         result = DateTime.Parse(dateString, culture, styles)
         outputBlock.Text += String.Format("{0} converted to {1} {2}.", _
                           dateString, result, result.Kind.ToString()) & vbCrLf
      Catch e As FormatException
         outputBlock.Text += String.Format("Unable to convert {0} to a date and time.", dateString) & vbCrLf
      End Try

      ' Attempt to convert a string in improper ISO 8601 format.
      dateString = "03/01/2009T10:00:00-5:00"
      Try
         result = DateTime.Parse(dateString, culture, styles)
         outputBlock.Text += String.Format("{0} converted to {1} {2}.", _
                           dateString, result, result.Kind.ToString()) & vbCrLf
      Catch e As FormatException
         outputBlock.Text += String.Format("Unable to convert {0} to a date and time.", dateString) & vbCrLf
      End Try

      ' 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 = CultureInfo.CreateSpecificCulture("fr-FR")
      styles = DateTimeStyles.AdjustToUniversal Or DateTimeStyles.AssumeLocal
      Try
         result = DateTime.Parse(dateString, culture, styles)
         outputBlock.Text += String.Format("{0} converted to {1} {2}.", _
                           dateString, result, result.Kind.ToString()) & vbCrLf
      Catch e As FormatException
         outputBlock.Text += String.Format("Unable to convert {0} to a date and time.", dateString) & vbCrLf
      End Try
   End Sub
End Module
'
' 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.
using System;
using System.Globalization;

public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      string dateString;
      CultureInfo culture;
      DateTimeStyles styles;
      DateTime result;

      // Parse a date and time with no styles.
      dateString = "03/01/2009 10:00 AM";
      culture = CultureInfo.CreateSpecificCulture("en-US");
      styles = DateTimeStyles.None;
      try
      {
         result = DateTime.Parse(dateString, culture, styles);
         outputBlock.Text += String.Format("{0} converted to {1} {2}.",
                           dateString, result, result.Kind.ToString()) + "\n";
      }
      catch (FormatException)
      {
         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;
      try
      {
         result = DateTime.Parse(dateString, culture, styles);
         outputBlock.Text += String.Format("{0} converted to {1} {2}.",
                           dateString, result, result.Kind.ToString()) + "\n";
      }
      catch (FormatException)
      {
         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;
      try
      {
         result = DateTime.Parse(dateString, culture, styles);
         outputBlock.Text += String.Format("{0} converted to {1} {2}.",
                           dateString, result, result.Kind.ToString()) + "\n";
      }
      catch (FormatException)
      {
         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";
      try
      {
         result = DateTime.Parse(dateString, culture, styles);
         outputBlock.Text += String.Format("{0} converted to {1} {2}.",
                           dateString, result, result.Kind.ToString()) + "\n";
      }
      catch (FormatException)
      {
         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 = CultureInfo.CreateSpecificCulture("fr-FR");
      styles = DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeLocal;
      try
      {
         result = DateTime.Parse(dateString, culture, styles);
         outputBlock.Text += String.Format("{0} converted to {1} {2}.",
                           dateString, result, result.Kind.ToString()) + "\n";
      }
      catch (FormatException)
      {
         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.