DateTime.Parse Method (String) (System)

Switch View :
ScriptFree
.NET Framework Class Library
DateTime.Parse Method (String)

Updated: October 2010

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

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

Visual Basic
Public Shared Function Parse ( _
	s As String _
) As DateTime
C#
public static DateTime Parse(
	string s
)
Visual C++
public:
static DateTime Parse(
	String^ s
)
F#
static member Parse : 
        s:string -> DateTime 

Parameters

s
Type: System.String
A string containing a date and time to convert.

Return Value

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

Exception Condition
ArgumentNullException

s is null.

FormatException

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

Remarks

The DateTime.Parse(String) method tries to convert the string representation of a date and time value to its DateTime equivalent. 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.

  • A string with a time but no date component.

  • A string that includes time zone information and conforms to ISO 8601. For example, the first of the following two strings designates the Coordinated Universal Time (UTC); the second designates the time in a time zone 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

This method attempts to parse s completely and avoid throwing a FormatException. It ignores unrecognized data if possible and fills in missing month, day, and year information with the current date. If s contains only a date and no time, this method assumes 12:00 midnight. If s contains only a time and no date, this method assumes the current date. If s includes a date component with a two-digit year, it is converted to a year in the current culture's current calendar based on the value of the Calendar.TwoDigitYearMax property. Any leading, inner, or trailing white space character in s is ignored. 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).

Important note Important

Because the string representation of a date and time must conform to a recognized pattern, applications should always use exception handling when calling the Parse(String) method to parse user input. Alternatively, you can call the DateTime.TryParse(String, DateTime) method to parse a date and time string and return a value that indicates whether the parse operation succeeded.

The string s is parsed using formatting information in the current DateTimeFormatInfo object, which is supplied implicitly by the current thread culture.

Important note Important

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

In most cases, the Parse(String) method returns a DateTime value whose Kind property is DateTimeKind.Unspecified. However, if the string to be parsed contains time zone information as defined by ISO 8601 or if it includes the older GMT designator, the Parse(String) method performs any necessary time conversion and returns a DateTime value whose date and time reflects the local time and whose Kind property is DateTimeKind.Local. The following example illustrates these string representations.

Visual Basic

Dim dateStrings() As String = {"2008-05-01T07:34:42-5:00", _
                               "2008-05-01 7:34:42Z", _
                               "Thu, 01 May 2008 07:34:42 GMT"}

For Each dateString As String In dateStrings
   Dim convertedDate As Date = Date.Parse(dateString)
   Console.WriteLine("Converted {0} to {1} time {2}.", _
                     dateString, _
                     convertedDate.Kind.ToString(), _
                     convertedDate)
Next 
' 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.                                             


C#

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.                                             


Notes to Callers

Formatting is influenced by properties of the current DateTimeFormatInfo object, which by default are derived from the Regional and Language Options item in Control Panel. One reason the Parse method can unexpectedly throw FormatException is if the current DateTimeFormatInfo.DateSeparator and DateTimeFormatInfo.TimeSeparator properties are set to the same value.

Examples

The following example demonstrates the Parse(String) method. It parses the string representation of several date and time values using the formatting conventions of the en-US culture, which is the current thread culture of the computer used to produce the example output. It handles the FormatException that is thrown when the method tries to parse the string representation of a date and time 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.

Visual Basic

Imports System.Globalization

Class DateTimeParser
   Public Shared Sub 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
      Dim dateValue As Date
      Dim dateString As String = "2/16/2008 12:15:12 PM"
      Try
         dateValue = Date.Parse(dateString)
         Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue)
      Catch e As FormatException
         Console.WriteLine("Unable to convert '{0}'.", dateString)
      End Try

      ' 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 = Date.Parse(dateString)
         Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue)
      Catch e As FormatException
         Console.WriteLine("Unable to convert '{0}'.", dateString)
      End Try

      ' Call another overload of Parse to successfully convert string
      ' formatted according to conventions of fr-FR culture.      
      Try
         dateValue = Date.Parse(dateString, New CultureInfo("fr-FR", False))
         Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue)
      Catch e As FormatException
         Console.WriteLine("Unable to convert '{0}'.", dateString)
      End Try

      ' Parse string with date but no time component.
      dateString = "2/16/2008"
      Try
         dateValue = Date.Parse(dateString)
         Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue)
      Catch e As FormatException
         Console.WriteLine("Unable to convert '{0}'.", dateString)
      End Try
   End Sub 
End Class 
' 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.


C#

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.


Version Information

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1
Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
See Also

Reference

Other Resources

Change History

Date

History

Reason

October 2010

Removed mention of DateTimeFormatInfo.GetAllDateTimePatterns.

Content bug fix.

Community Content

R Petrusha - MSFT
RE: A bug parsing GMT dates/times?

That is some serious insanity on Microsoft's part that they didn't fix this bug back in 2.0 and instead created one of the most deceitful APIs I've ever seen in the .NET CLR.  The CLR actively lies to us regarding dates formatted as "R".

A Bug?

Quite frankly, I don't see what the "bug" is, much less what it is that's deceitful. As I pointed out in my response to the previous post, the DateTime.Parse(String) method works as documented.

The problem, it seems to me, is that because the "R" standard format string is specified as the output format to be used for a DateTime value in the call to the DateTime.ToString method, it is somehow assumed that the parsing operation should also somehow cooperate in round-tripping the original string. But parsing and formatting are two independent operations here. If you want to round-trip the string representation of a DateTime value, you have to make that explicit for each operation.

In the example in previous post, for instance, the string "Sat, 01 Nov 2008 19:35:00 GMT" did not successfully round-trip. However, by explicitly specifying the format of the string to be parsed, it is possible to round-trip the original string. The following code does that:

      string dts2 = "Sat, 01 Nov 2008 19:35:00 GMT";    // RFC1123
      Console.WriteLine(DateTime.ParseExact(dts2, "R", null).ToString("R"));    // Displays Sat, 01 Nov 2008 19:35:00 GMT

--Ron Petrusha
Common Language Runtime User Education
Microsoft Corporation


R Petrusha - MSFT
A bug parsing GMT dates/times?

I made the following experiment and got a result that is incorrect:

string dts2 = "Sat, 01 Nov 2008 19:35:00 GMT";    // RFC1123
Console.WriteLine( DateTime.Parse(dts2).ToString("R") );

Now, there I am specifying that the input string is in RFC1123 format (UTC) so the output should be the same as the input, yet the result of the parse is quite unexpected, it translates the input string to local time (my system is at UTC-5:00):

"Sat, 01 Nov 2008 14:35:00 GMT"

The input string clearly indicates TWICE that it is UTC, first by the GMT at the end (as mandated) and second by means of the R parse specifier.
My system is running .NET 4.0 on Windows 7 Home Premium 64 bits.

Why This Behavior Is Expected

The parsing and formatting here are two separate operations. Your statement that the "input string clearly indicates TWICE that it is UTC..." is not at all accurate, since there is only one input string, which is supplied to the Parse method so that it can be converted to a DateTime value. The "R" is a standard format string; it indicates that the value of the current DateTime instance, whatever it happens to be, should be converted to the string representation of a date and time in RFC 1123 format. These are two separate operations, so let's see what each one does:

  • DateTime.Parse(String) converts the string representation of a date and time to a date and time. Note, though, that the documentation (see the Remarks section above) indicates that some conversion is performed on the string: "In most cases, the Parse(String) method returns a DateTime value whose Kind property is DateTimeKind.Unspecified. However, if the string to be parsed contains time zone information as defined by ISO 8601 or if it includes the older GMT designator, the Parse(String) method performs any necessary time conversion and returns a DateTime value whose date and time reflects the local time and whose Kind property is DateTimeKind.Local." So the UTC time reflected by your string was converted to an equivalent local time in your time zone.
  • DateTime.ToString("R") converts the value of a DateTime instance to a date and time string in RFC 1123 format. However, it performs no time conversion. According to the documentation from the Standard Date and Time Format Strings topic at http://msdn.microsoft.com/en-us/library/az4se3k1.aspx,"Although the RFC 1123 standard expresses a time as Coordinated Universal Time (UTC), the formatting operation does not modify the value of the DateTime or DateTimeOffset object that is being formatted. Therefore, the application must convert the date and time value to UTC before it performs the formatting operation."

We can see this in the following code, which displays the DateTime value returned by parsing dts2:

      string dts2 = "Sat, 01 Nov 2008 19:35:00 GMT";
      DateTime dt2 = DateTime.Parse(dts2);
Console.WriteLine("{0} --> {1:g}, {2}", dts2, dt2, dt2.Kind);
      Console.WriteLine("{0:g} --> {1}", dt2, dt2.ToString("R"));

The output in the U.S. Pacific Standard Time zone is:

Sat, 01 Nov 2008 19:35:00 GMT --> 11/1/2008 12:35 PM, Local
11/1/2008 12:35 PM --> Sat, 01 Nov 2008 12:35:00 GMT

So the original parsing operation returns a DateTime value that reflects the local time, and the "R" format string simply formats the DateTime value in RFC 1123 format but doesn't perform any conversion. (The decision to simply format the existing date and time value rather than perform a time conversion was probably made to maintain backward compatibility when the .NET Framework Version 2.0 was introduced.) This means that, if you want to round-trip a UTC date and time value, you'll have to perform the conversion yourself. The following code does that (note that it requires that the System.Globalization namespace be imported):

      string dts2 = "Sat, 01 Nov 2008 19:35:00 GMT";   
      DateTime dt2 = DateTime.Parse(dts2, null, System.Globalization.DateTimeStyles.AdjustToUniversal);
Console.WriteLine("{0} --> {1:g}, {2}", dts2, dt2, dt2.Kind);
      Console.WriteLine("{0:g} --> {1}", dt2, dt2.ToString("R"));

The output in the U.S. Pacific Standard Time Zone is:

Sat, 01 Nov 2008 19:35:00 GMT --> 11/1/2008 7:35 PM, Utc
11/1/2008 7:35 PM --> Sat, 01 Nov 2008 19:35:00 GMT

--Ron Petrusha
Common Language Runtime User Education
Microsoft Corporation

 


R Petrusha - MSFT
Why it is 1949 ,but not 2049?

DateTime.Parse("24-Jan-49") will return 1/24/1949, why?

Is this a bug or .Net Framework just will always return 19xx when parsing DD-MM-RR format datetime strings?

Interpreting Two-Digit Years

Two-digit years are interpreted based on the value of the Calendar.TwoDigitYearMax property of the calendar used in the parsing operation. The Calendar.TwoDigitYearMax property defines the last year of a 100-year range
that is used for interpreting two-digit years. In the case of the Gregorian calendar, the most common value is 2029, which means that two-digit years from 30-99 are interpreted as 1930-1999, and two-digit years from 00 to 29 are interpreted as 2000-2029.

To change this value, you have to instantiate writable GregorianCalendar and DateTimeFormatInfo objects and assign the appropriate end value to the GregorianCalendar.TwoDigitYearMax property. The following C# code does that and interprets any two-digit year as belonging in the current century for a current culture that uses the Gregorian calendar.

using System;
using System.Globalization;
using System.Threading;
public class Example
{
public static void Main()
{
string value = "24-Jan-49";

Calendar cal = (Calendar) CultureInfo.CurrentCulture.Calendar.Clone();
Console.WriteLine("Two Digit Year Range: {0} - {1}",
cal.TwoDigitYearMax - 99, cal.TwoDigitYearMax);

Console.WriteLine("{0:d}", DateTime.Parse(value));
Console.WriteLine();

cal.TwoDigitYearMax = 2099;
CultureInfo culture = (CultureInfo) CultureInfo.CurrentCulture.Clone();
culture.DateTimeFormat.Calendar = cal;
Thread.CurrentThread.CurrentCulture = culture;
Console.WriteLine("Two Digit Year Range: {0} - {1}",
cal.TwoDigitYearMax - 99, cal.TwoDigitYearMax);
Console.WriteLine("{0:d}", DateTime.Parse(value));
}
}
// The example displays the following output:
// Two Digit Year Range: 1930 - 2029
// 1/24/1949
//
// Two Digit Year Range: 2000 - 2099
// 1/24/2049


We'll modify the documentation to note that the TwoDigitYearMax property is used in parsing two-digit years. Thanks for asking this question.

--Ron Petrusha
Common Language Runtime User Education
Microsoft Corporation


gajop
Return the working format
It would be beneficial if we could get the correct format that successfully parsed the DateTime, so that format could be passed to the .ParseExact method (http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx), or otherwise saved for further use. The reason for this is that it is likely when a document is parsed that the same formatting will appear over and over, allowing for quite likely faster parse calls if the format is passed, instead of using this general function.

R Petrusha - MSFT
Option to specify format?
A possible addition would be to specify the format of input string, to circumvent cases where the parser cannot determine the value itself.
Consider the following:

DateTime.Parse("20100803"); // Fails with FormatException
DateTime.Parse("20100803", "yyyyMMdd"); // Proposed solution

The Option to Specify a Format Already Exists

Two existing methods allow you to specify the format or formats that the input string can have. The first is DateTime.ParseExact (http://msdn.microsoft.com/en-us/library/system.datetime.parseexact.aspx), which has three overloads. The second is DateTime.TryParseExact (http://msdn.microsoft.com/en-us/library/system.datetime.tryparseexact.aspx), which has two overloads. The overloads of these methods allow you to specify either a single format string that the parsed string must conform to, or to provide array of format strings, one of which must correspond to the parsed string.

--Ron Petrusha
CLR Developer Content Team
Microsoft Corporation


R Petrusha - MSFT
Exception

The above code throws exception when we run it on Windows 7 Professional N. Please try reproducing it in that particular edition

Exception Cannot Be Reproduced

There are two examples above, written in two different languages. I'm not certain which one is causing problems for you. However, we can't reproduce the exception on Windows 7 Professional Edition. Note that these examples are culture-sensitive; they assume that the current culture is en-US. If that is not the case, an exception is likely to be thrown.

--Ron Petrusha
Developer Division User Education
Microsoft Corporation