Export (0) Print
Expand All
3 out of 5 rated this helpful - Rate this topic

DateTime.Parse Method

Converts the string representation of a date and time to its DateTime equivalent.

This member is overloaded. For complete information about this member, including syntax, usage, and examples, click a name in the overload list.

  Name Description
Public method Static member Parse(String) Converts the string representation of a date and time to its DateTime equivalent.
Public method Static member Parse(String, IFormatProvider) Converts the string representation of a date and time to its DateTime equivalent by using culture-specific format information.
Public method Static member Parse(String, IFormatProvider, DateTimeStyles) Converts the string representation of a date and time to its DateTime equivalent by using culture-specific format information and formatting style.
Top

In this section:

Overloaded method syntax
Parameters
Return value
Exceptions
Which method do I call?
The string to parse
Parsing and cultural conventions
Parsing and style elements
Examples:
       DateTime.Parse(String)
       DateTime.Parse(String, IFormatProvider)
       DateTime.Parse(String, IFormatProvider, DateTimeStyles)
Version information

Overloaded method syntax

For additional guidance on choosing an overload, see Which method do I call?

DateTime.Parse(String s )

For the conversion, uses the formatting conventions of the current thread culture and interprets the string based on the DateTimeStyles.AllowWhiteSpaces style flag (example).

DateTime.Parse(String s , IFormatProvider provider )

For the conversion, uses the formatting conventions of a specified culture and interprets the string based on the DateTimeStyles.AllowWhiteSpaces style flag (example).

DateTime.Parse(String s , IFormatProvider provider , DateTypeStyles styles )

For the conversion, uses the formatting conventions of a specified culture and interprets the string based on specified style flags (example).

Parameters

This is a complete list of parameters for the Parse method. For the parameters used by each overload, see the overload syntax above.

Parameter

Type

Description

s

String

A string that contains the date and time to convert. See The string to parse.

Default value: None (parameter is used by all overloads)

provider

IFormatProvider

An object that supplies culture-specific formatting information about s. See Parsing and cultural conventions.

Default value: CultureInfo.CurrentCulture

styles

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 DateTimeStyles.None. See Parsing and style elements.

Default value: DateTimeStyles.AllowWhiteSpaces

Return value

Type: DateTime
An object that is equivalent to the date and time contained in s.

Generally, the Parse method returns a DateTime object whose Kind property is DateTimeKind.Unspecified. However, the Parse method may also perform time zone conversion and set the value of the Kind property differently, depending on the values of the s and styles parameters:

If

Time zone conversion

Kind property

s contains time zone information.

The date and time is converted to the time in the local time zone.

DateTimeKind.Local

s contains time zone information, and styles includes the AdjustToUniversal flag.

The date and time is converted to Coordinated Universal Time (UTC).

DateTimeKind.Utc

s contains the Z or GMT time zone designator, and styles includes the RoundtripKind flag.

The date and time are interpreted as UTC.

DateTimeKind.Utc

The following example converts date strings that contain time zone information to the time in the local time zone:

using System;

public class Example
{
   public static void Main()
   {
      string[] dateStrings = {"2008-05-01T07:34:42-5:00", 
                              "2008-05-01 7:34:42Z", 
                              "Thu, 01 May 2008 07:34:42 GMT"};
      foreach (string dateString in dateStrings)
      {
         DateTime convertedDate = DateTime.Parse(dateString);
         Console.WriteLine("Converted {0} to {1} time {2}", 
                           dateString, 
                           convertedDate.Kind.ToString(), 
                           convertedDate);
      }                              
   }
}
// These calls to the DateTime.Parse method display the following output: 
//  Converted 2008-05-01T07:34:42-5:00 to Local time 5/1/2008 5:34:42 AM 
//  Converted 2008-05-01 7:34:42Z to Local time 5/1/2008 12:34:42 AM 
//  Converted Thu, 01 May 2008 07:34:42 GMT to Local time 5/1/2008 12:34:42 AM                                             

You can also preserve the value of a date and time's Kind property during a formatting and parsing operation by using the DateTimeStyles.RoundTripKind flag. The following example illustrates how the RoundTripKind flag affects the parsing operation on DateTime values that are converted to strings by using the "o", "r", or "u" format specifier.

   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)
   {
      Console.WriteLine(formattedDate);
      DateTime roundtripDate = DateTime.Parse(formattedDate, null, 
                                              DateTimeStyles.RoundtripKind);                        
      Console.WriteLine("   With RoundtripKind flag: {0} {1} time.", 
                        roundtripDate, roundtripDate.Kind);                                          
      DateTime noRoundtripDate = DateTime.Parse(formattedDate, null, 
                                                DateTimeStyles.None);
      Console.WriteLine("   Without RoundtripKind flag: {0} {1} time.", 
                         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.      

Exceptions

Exception

Condition

Thrown by

ArgumentNullException

s is null.

All overloads

FormatException

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

All overloads

ArgumentException

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

Parse(String, IFormatProvider, DateTimeStyles)

Which method do I call?

To

Call

Parse a date and time string by using the conventions of the current culture.

Parse(String) overload

Parse a date and time string by using the conventions of a specific culture.

Parse(String, IFormatProvider) overload (see Parsing and Cultural Conventions)

Parse a date and time string with special style elements (such as white space or no white space).

Parse(String, IFormatProvider, DateTimeStyles) overload

Parse a date and time string and perform a conversion to UTC or local time.

Parse(String, IFormatProvider, DateTimeStyles) overload

Parse a date and time string without handling exceptions.

DateTime.TryParse method

Restore (round-trip) a date and time value created by a formatting operation.

Pass the "o" or "r" standard format string to the ToString(String) method, and call the Parse(String, IFormatProvider, DateTimeStyles) overload with DateTimeStyles.RoundTripKind

Parse a date and time string in a fixed format across machine (and possibly cultural) boundaries.

DateTime.ParseExact or DateTime.TryParseExact method

The string to parse

The Parse method tries to convert the string representation of a date and time value to its DateTime equivalent. It tries to parse s completely without throwing a FormatException exception.

Important note Important

Because the string representation of a date and time must conform to a recognized pattern, you should always use exception handling when calling the Parse method to parse user input. If you don't want to handle exceptions, you can call the DateTime.TryParse method to parse the date and time string; this method returns a value that indicates whether the parse operation succeeded.

The string to be parsed can take any of the following forms:

  • A string with a date and a time component.

  • A string with a date but no time component. If the time component is absent, the method assumes 12:00 midnight. If the date component has a two-digit year, it is converted to a year based on the Calendar.TwoDigitYearMax of the current culture's current calendar or the specified culture's current calendar (if you use an overload with a non-null provider argument).

  • A string with a time but no date component. The method assumes the current date unless you call the Parse(String, IFormatProvider, DateTimeStyles) overload and include DateTimeStyles.NoCurrentDateDefault in the styles parameter, in which case the method assumes January 1, 0001.

  • A string that includes time zone information and conforms to ISO 8601. In the following examples, the first string designates Coordinated Universal Time (UTC), and the second string designates the time in a time zone that's seven hours earlier than UTC:

    2008-11-01T19:35:00.0000000Z
    2008-11-01T19:35:00.0000000-07:00

  • A string that includes the GMT designator and conforms to the RFC 1123 time format; for example:

    Sat, 01 Nov 2008 19:35:00 GMT

  • A string that includes the date and time along with time zone offset information; for example:

    03/01/2009 05:42:00 -5:00

If s is the string representation of a leap day in a leap year in the calendar used by the parsing method (see Parsing and cultural conventions), the Parse method parses s successfully. If s is the string representation of a leap day in a non-leap year, the method throws a FormatException exception.

Because the Parse method tries to parse the string representation of a date and time by using the formatting rules of the current or specified culture, trying to parse a string across different cultures can fail. To parse a specific date and time format across different locales, use one of the overloads of the DateTime.ParseExact method and provide a format specifier.

Parsing and cultural conventions

All overloads of the Parse method are culture-sensitive unless the string to be parsed conforms to the ISO 8601 pattern. The parsing operation uses the formatting information in a DateTimeFormatInfo object that is derived as follows:

When formatting information is derived from a DateTimeFormatInfo object, the DateTimeFormatInfo.Calendar property defines the calendar used in the parsing operation.

If you parse a date and time string by using a DateTimeFormatInfo object with customized settings that are different from those of a standard culture, use the ParseExact method instead of the Parse method to improve the chances for a successful conversion. A non-standard date and time string can be complicated and difficult to parse. The Parse method tries to parse a string with several implicit parse patterns, all of which might fail. In contrast, the ParseExact method requires you to explicitly designate one or more exact parse patterns that are likely to succeed. For more information, see the "DateTimeFormatInfo and Dynamic Data" section in the DateTimeFormatInfo topic.

Parsing and style elements

All Parse overloads ignore leading, inner, or trailing white-space characters in s. The date and time can be bracketed with a pair of leading and trailing NUMBER SIGN characters ("#", U+0023), and can be trailed with one or more NULL characters (U+0000).

In addition, the Parse(String, IFormatProvider, DateTimeStyles) overload has a styles parameter that consists of one or more members of the DateTimeStyles enumeration. This parameter defines how s should be interpreted and how the parse operation should convert s to a date and time. The following table describes the effect of each DateTimeStyles member on the parse operation.

DateTimeStyles member

Effect on conversion

AdjustToUniversal

Parses s and, if necessary, converts it to UTC, as follows:

  • If s includes a time zone offset, or if s contains no time zone information but styles includes the 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 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

This value is ignored. Inner white space is always permitted in the date and time elements of s.

AllowLeadingWhite

This value is ignored. Leading white space is always permitted in the date and time elements of s.

AllowTrailingWhite

This value is ignored. Trailing white space is always 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 None.

AssumeLocal

Specifies that if s lacks any time zone information, local time is assumed. Unless the 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, UTC is assumed. Unless the 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 and by using the "o", "r", or "u" standard format specifier.

DateTime.Parse(String) example

The following example parses the string representation of several date and time values by using default provider and style values: the formatting conventions of the en-US culture, which is the current thread culture of the computer used to produce the example output, and the AllowWhiteSpaces style flag. It handles the FormatException exception that is thrown when the method tries to parse the string representation of a date and time by using some other culture's formatting conventions. It also shows how to successfully parse a date and time value that does not use the formatting conventions of the current thread culture.

using System;
using System.Globalization;

public class DateTimeParser
{
   public static void Main()
   {
      // Assume the current culture is en-US.  
      // The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds. 

      // Use standard en-US date and time value
      DateTime dateValue;
      string dateString = "2/16/2008 12:15:12 PM";
      try {
         dateValue = DateTime.Parse(dateString);
         Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
      }   
      catch (FormatException) {
         Console.WriteLine("Unable to convert '{0}'.", dateString);
      }

      // Reverse month and day to conform to the fr-FR culture. 
      // The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.
      dateString = "16/02/2008 12:15:12";
      try {
         dateValue = DateTime.Parse(dateString);
         Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
      }   
      catch (FormatException) {
         Console.WriteLine("Unable to convert '{0}'.", dateString);
      }

      // Call another overload of Parse to successfully convert string 
      // formatted according to conventions of fr-FR culture.       
      try {
         dateValue = DateTime.Parse(dateString, new CultureInfo("fr-FR", false));
         Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
      }   
      catch (FormatException) {
         Console.WriteLine("Unable to convert '{0}'.", dateString);
      }

      // Parse string with date but no time component.
      dateString = "2/16/2008";
      try {
         dateValue = DateTime.Parse(dateString);
         Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
      }   
      catch (FormatException) {
         Console.WriteLine("Unable to convert '{0}'.", dateString);
      }   
   }
}
// The example displays the following output to the console: 
//       '2/16/2008 12:15:12 PM' converted to 2/16/2008 12:15:12 PM. 
//       Unable to convert '16/02/2008 12:15:12'. 
//       '16/02/2008 12:15:12' converted to 2/16/2008 12:15:12 PM. 
//       '2/16/2008' converted to 2/16/2008 12:00:00 AM.

DateTime.Parse(String, IFormatProvider) example

The following example parses an array of date strings by using the conventions of the en-US, fr-FR, and de-DE cultures. It demonstrates that the string representations of a single date can be interpreted differently across different cultures.

using System;
using System.Globalization;

public class ParseDate
{
   public static void Main()
   {
      // Define cultures to be used to parse dates.
      CultureInfo[] cultures = {CultureInfo.CreateSpecificCulture("en-US"), 
                                CultureInfo.CreateSpecificCulture("fr-FR"), 
                                CultureInfo.CreateSpecificCulture("de-DE")};
      // Define string representations of a date to be parsed. 
      string[] dateStrings = {"01/10/2009 7:34 PM", 
                              "10.01.2009 19:34", 
                              "10-1-2009 19:34" };
      // Parse dates using each culture. 
      foreach (CultureInfo culture in cultures)
      {
         DateTime dateValue;
         Console.WriteLine("Attempted conversions using {0} culture.", 
                           culture.Name);
         foreach (string dateString in dateStrings)
         {
            try {
               dateValue = DateTime.Parse(dateString, culture);
               Console.WriteLine("   Converted '{0}' to {1}.",
                                 dateString, dateValue.ToString("f", culture));
            }
            catch (FormatException) {
               Console.WriteLine("   Unable to convert '{0}' for culture {1}.", 
                                 dateString, culture.Name);
            }
         }
         Console.WriteLine();
      }                                                                                     
   }
}
// The example displays the following output to the console: 
//       Attempted conversions using en-US culture. 
//          Converted '01/10/2009 7:34 PM' to Saturday, January 10, 2009 7:34 PM. 
//          Converted '10.01.2009 19:34' to Thursday, October 01, 2009 7:34 PM. 
//          Converted '10-1-2009 19:34' to Thursday, October 01, 2009 7:34 PM. 
//        
//       Attempted conversions using fr-FR culture. 
//          Converted '01/10/2009 7:34 PM' to jeudi 1 octobre 2009 19:34. 
//          Converted '10.01.2009 19:34' to samedi 10 janvier 2009 19:34. 
//          Converted '10-1-2009 19:34' to samedi 10 janvier 2009 19:34. 
//        
//       Attempted conversions using de-DE culture. 
//          Converted '01/10/2009 7:34 PM' to Donnerstag, 1. Oktober 2009 19:34. 
//          Converted '10.01.2009 19:34' to Samstag, 10. Januar 2009 19:34. 
//          Converted '10-1-2009 19:34' to Samstag, 10. Januar 2009 19:34.

DateTime.Parse(String, IFormatProvider, DateTimeStyles) example

The following example demonstrates the Parse(String, IFormatProvider, DateTimeStyles) method and displays the value of the Kind property of the resulting DateTime values.

using System;
using System.Globalization;

public class ParseDateExample
{
   public static void Main()
   {
      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);
         Console.WriteLine("{0} converted to {1} {2}.", 
                           dateString, result, result.Kind.ToString());
      }
      catch (FormatException) {
         Console.WriteLine("Unable to convert {0} to a date and time.", 
                           dateString);
      }      

      // Parse the same date and time with the AssumeLocal style.
      styles = DateTimeStyles.AssumeLocal;
      try {
         result = DateTime.Parse(dateString, culture, styles);
         Console.WriteLine("{0} converted to {1} {2}.", 
                           dateString, result, result.Kind.ToString());
      }
      catch (FormatException) {
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString);
      }      

      // 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);
         Console.WriteLine("{0} converted to {1} {2}.", 
                           dateString, result, result.Kind.ToString());
      }
      catch (FormatException) {
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString);
      }      

      // 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);
         Console.WriteLine("{0} converted to {1} {2}.", 
                           dateString, result, result.Kind.ToString());
      }                     
      catch (FormatException) {
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString);
      }      

      // 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);
         Console.WriteLine("{0} converted to {1} {2}.", 
                           dateString, result, result.Kind.ToString());
      }
      catch (FormatException) {
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString);
      }      
   }
}
// The example displays the following output to the console: 
//       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

.NET Framework

All overloads are supported in: 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

All overloads are supported in: 4, 3.5 SP1

Portable Class Library

All overloads are supported

.NET for Windows Store apps

All overloads are supported in: Windows 8

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.