Redigeeri

Jagamisviis:


DateTime.Parse Method

Definition

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

Overloads

Parse(String)

Converts the string representation of a date and time to its DateTime equivalent by using the conventions of the current culture.

Parse(ReadOnlySpan<Char>, IFormatProvider)

Parses a span of characters into a value.

Parse(String, IFormatProvider)

Converts the string representation of a date and time to its DateTime equivalent by using culture-specific format information.

Parse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles)

Converts a memory span that contains string representation of a date and time to its DateTime equivalent by using culture-specific format information and a formatting style.

Parse(String, IFormatProvider, DateTimeStyles)

Converts the string representation of a date and time to its DateTime equivalent by using culture-specific format information and a formatting style.

Examples

Numerous examples that call the DateTime.Parse method are interspersed throughout the Remarks section of this article and in the documentation for the individual DateTime.Parse overloads.

Note

Some C# examples in this article run in the Try.NET inline code runner and playground. Select Run to run an example in an interactive window. Once you execute the code, you can modify it and run the modified code by selecting Run again. The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.

The local time zone of the Try.NET inline code runner and playground is Coordinated Universal Time, or UTC. This might affect the behavior and the output of examples that illustrate the DateTime, DateTimeOffset, and TimeZoneInfo types and their members.

You can also download a complete set of DateTime.Parse examples, which are included in a .NET Core project for C#.

Remarks

In this section:

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 that must be in a particular format. DateTime.ParseExact or DateTime.TryParseExact
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 the input string completely without throwing a FormatException exception.

Important

If the parsing operation fails because of an unrecognized string format, the Parse method throws a FormatException, whereas the TryParse method returns false. Because exception handling can be expensive, you should use Parse when the parsing operation is expected to succeed because the input source is trusted. TryParse is preferable when parsing failures are likely, particularly because an input source is not trusted, or you have reasonable default values to substitute for strings that do not parse successfully.

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 date component that includes only the month and the year but no day component. The method assumes the first day of the month.

  • A string with a date component that includes only the month and the day but no year component. The method assumes the current year.

  • 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 argument, in which case the method assumes a date of January 1, 0001.

  • A string with a time component that includes only the hour and an AM/PM designator, with no date component. The method assumes the current date and a time with no minutes and no seconds. You can change this behavior by calling the Parse(String, IFormatProvider, DateTimeStyles) overload and include DateTimeStyles.NoCurrentDateDefault in the styles argument, in which case the method assumes a date of 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 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"

The following example parses strings in each of these formats by using the formatting conventions of the current culture, which in this case is the en-US culture:

using System;

public class Example
{
   public static void Main()
   {
      (string dateAsString, string description)[]  dateInfo = { ("08/18/2018 07:22:16", "String with a date and time component"),
                                                                ("08/18/2018", "String with a date component only"),
                                                                ("8/2018", "String with a month and year component only"),
                                                                ("8/18", "String with a month and day component only"),
                                                                ("07:22:16", "String with a time component only"),
                                                                ("7 PM", "String with an hour and AM/PM designator only"),
                                                                ("2018-08-18T07:22:16.0000000Z", "UTC string that conforms to ISO 8601"),
                                                                ("2018-08-18T07:22:16.0000000-07:00", "Non-UTC string that conforms to ISO 8601"),
                                                                ("Sat, 18 Aug 2018 07:22:16 GMT", "String that conforms to RFC 1123"),
                                                                ("08/18/2018 07:22:16 -5:00", "String with date, time, and time zone information" ) };

      Console.WriteLine($"Today is {DateTime.Now:d}\n");

      foreach (var item in dateInfo) {
         Console.WriteLine($"{item.description + ":",-52} '{item.dateAsString}' --> {DateTime.Parse(item.dateAsString)}");
      }
   }
}
// The example displays output like the following:
//   Today is 2/22/2018
//
//   String with a date and time component:               '08/18/2018 07:22:16' --> 8/18/2018 7:22:16 AM
//   String with a date component only:                   '08/18/2018' --> 8/18/2018 12:00:00 AM
//   String with a month and year component only:         '8/2018' --> 8/1/2018 12:00:00 AM
//   String with a month and day component only:          '8/18' --> 8/18/2018 12:00:00 AM
//   String with a time component only:                   '07:22:16' --> 2/22/2018 7:22:16 AM
//   String with an hour and AM/PM designator only:       '7 PM' --> 2/22/2018 7:00:00 PM
//   UTC string that conforms to ISO 8601:                '2018-08-18T07:22:16.0000000Z' --> 8/18/2018 12:22:16 AM
//   Non-UTC string that conforms to ISO 8601:            '2018-08-18T07:22:16.0000000-07:00' --> 8/18/2018 7:22:16 AM
//   String that conforms to RFC 1123:                    'Sat, 18 Aug 2018 07:22:16 GMT' --> 8/18/2018 12:22:16 AM
//   String with date, time, and time zone information:   '08/18/2018 07:22:16 -5:00' --> 8/18/2018 5:22:16 AM
module Parse6

open System

let  dateInfo = 
    [ "08/18/2018 07:22:16", "String with a date and time component"
      "08/18/2018", "String with a date component only"
      "8/2018", "String with a month and year component only"
      "8/18", "String with a month and day component only"
      "07:22:16", "String with a time component only"
      "7 PM", "String with an hour and AM/PM designator only"
      "2018-08-18T07:22:16.0000000Z", "UTC string that conforms to ISO 8601"
      "2018-08-18T07:22:16.0000000-07:00", "Non-UTC string that conforms to ISO 8601"
      "Sat, 18 Aug 2018 07:22:16 GMT", "String that conforms to RFC 1123"
      "08/18/2018 07:22:16 -5:00", "String with date, time, and time zone information" ]

printfn $"Today is {DateTime.Now:d}\n"

for dateAsString, description in dateInfo do
    printfn $"""{description + ":",-52} '{dateAsString}' --> {DateTime.Parse(dateAsString)}"""


// The example displays output like the following:
//   Today is 2/22/2018
//
//   String with a date and time component:               '08/18/2018 07:22:16' --> 8/18/2018 7:22:16 AM
//   String with a date component only:                   '08/18/2018' --> 8/18/2018 12:00:00 AM
//   String with a month and year component only:         '8/2018' --> 8/1/2018 12:00:00 AM
//   String with a month and day component only:          '8/18' --> 8/18/2018 12:00:00 AM
//   String with a time component only:                   '07:22:16' --> 2/22/2018 7:22:16 AM
//   String with an hour and AM/PM designator only:       '7 PM' --> 2/22/2018 7:00:00 PM
//   UTC string that conforms to ISO 8601:                '2018-08-18T07:22:16.0000000Z' --> 8/18/2018 12:22:16 AM
//   Non-UTC string that conforms to ISO 8601:            '2018-08-18T07:22:16.0000000-07:00' --> 8/18/2018 7:22:16 AM
//   String that conforms to RFC 1123:                    'Sat, 18 Aug 2018 07:22:16 GMT' --> 8/18/2018 12:22:16 AM
//   String with date, time, and time zone information:   '08/18/2018 07:22:16 -5:00' --> 8/18/2018 5:22:16 AM

Public Module Strings
   Public Sub Main()
      Dim dateInfo() As (dateAsString As String, description As String) = 
                     { ("08/18/2018 07:22:16", "String with a date and time component"),
                       ("08/18/2018", "String with a date component only"),
                       ("8/2018", "String with a month and year component only"),
                       ("8/18", "String with a month and day component only"),
                       ("07:22:16", "String with a time component only"),
                       ("7 PM", "String with an hour and AM/PM designator only"),
                       ("2018-08-18T07:22:16.0000000Z", "UTC string that conforms to ISO 8601"),   
                       ("2018-08-18T07:22:16.0000000-07:00", "Non-UTC string that conforms to ISO 8601"),
                       ("Sat, 18 Aug 2018 07:22:16 GMT", "String that conforms to RFC 1123"),
                       ("08/18/2018 07:22:16 -5:00", "String with date, time, and time zone information" ) }
   
      Console.WriteLine($"Today is {Date.Now:d}{vbCrLf}")
      
      For Each item in dateInfo
         Console.WriteLine($"{item.description + ":",-52} '{item.dateAsString}' --> {DateTime.Parse(item.dateAsString)}")        
      Next
   End Sub
End Module
' The example displays output like the following:
'   Today is 2/22/2018
'   
'   String with a date and time component:               '08/18/2018 07:22:16' --> 8/18/2018 7:22:16 AM
'   String with a date component only:                   '08/18/2018' --> 8/18/2018 12:00:00 AM
'   String with a month and year component only:         '8/2018' --> 8/1/2018 12:00:00 AM
'   String with a month and day component only:          '8/18' --> 8/18/2018 12:00:00 AM
'   String with a time component only:                   '07:22:16' --> 2/22/2018 7:22:16 AM
'   String with an hour and AM/PM designator only:       '7 PM' --> 2/22/2018 7:00:00 PM
'   UTC string that conforms to ISO 8601:                '2018-08-18T07:22:16.0000000Z' --> 8/18/2018 12:22:16 AM
'   Non-UTC string that conforms to ISO 8601:            '2018-08-18T07:22:16.0000000-07:00' --> 8/18/2018 7:22:16 AM
'   String that conforms to RFC 1123:                    'Sat, 18 Aug 2018 07:22:16 GMT' --> 8/18/2018 12:22:16 AM
'   String with date, time, and time zone information:   '08/18/2018 07:22:16 -5:00' --> 8/18/2018 5:22:16 AM

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

Because the Parse method tries to parse the string representation of a date and time by using the formatting rules of the current or a 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 (which is represented by s in the following table) conforms to the ISO 8601 pattern. The parsing operation uses the formatting information in a DateTimeFormatInfo object that is derived as follows:

Important

Eras in the Japanese calendars are based on the emperor's reign and are therefore expected to change. For example, May 1, 2019 marked the beginning of the Reiwa era in the JapaneseCalendar and JapaneseLunisolarCalendar. Such a change of era affects all applications that use these calendars. For more information and to determine whether your applications are affected, see Handling a new era in the Japanese calendar in .NET. For information on testing your applications on Windows systems to ensure their readiness for the era change, see Prepare your application for the Japanese era change. For features in .NET that support calendars with multiple eras and for best practices when working with calendars that support multiple eras, see Working with eras.

If you call And provider is Formatting information is derived from
Parse(String) - The current culture (DateTimeFormatInfo.CurrentInfo property)
Parse(String, IFormatProvider) or Parse(String, IFormatProvider, DateTimeStyles) a DateTimeFormatInfo object The specified DateTimeFormatInfo object
Parse(String, IFormatProvider) or Parse(String, IFormatProvider, DateTimeStyles) null The current culture (DateTimeFormatInfo.CurrentInfo property)
Parse(String, IFormatProvider) or Parse(String, IFormatProvider, DateTimeStyles) a CultureInfo object The CultureInfo.DateTimeFormat property
Parse(String, IFormatProvider) or Parse(String, IFormatProvider, DateTimeStyles) Custom IFormatProvider implementation The IFormatProvider.GetFormat method

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.

Important

Note that the formatting conventions for a particular culture are dynamic and can be subject to change. This means that parsing operations that depend on the formatting conventions of the default (current) culture or that specify an IFormatProvider object that represents a culture other than the invariant culture can unexpectedly fail if any of the following occurs:

  • The culture-specific data has changed between major or minor versions of the .NET Framework or as the result of an update to the existing version of the .NET Framework.
  • The culture-specific data reflects user preferences, which can vary from machine to machine or session to session.
  • The culture-specific data represents a replacement culture that overrides the settings of a standard culture or a custom culture.

To prevent the difficulties in parsing data and time strings that are associated with changes in cultural data, you can parse date and time strings by using the invariant culture, or you can call the ParseExact or TryParseExact method and specify the exact format of the string to be parsed. If you are serializing and deserializing date and time data, you can either use the formatting conventions of the invariant culture, or you can serialize and deserialize the DateTime value in a binary format.

For more information see the "Dynamic culture data" section in the CultureInfo topic and the "Persisting DateTime values" section in the DateTime topic.

Parsing and style elements

All Parse overloads ignore leading, inner, or trailing white-space characters in the input string (which is represented by s in the following table). 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.

The return value and DateTime.Kind

The DateTime.Parse overloads return a DateTime value whose Kind property includes time zone information. It can indicate that the time is:

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 {dateString} to {convertedDate.Kind} time {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
open System

let dateStrings = 
    [ "2008-05-01T07:34:42-5:00"
      "2008-05-01 7:34:42Z"
      "Thu, 01 May 2008 07:34:42 GMT" ]

for dateString in dateStrings do
    let convertedDate = DateTime.Parse dateString
    printfn $"Converted {dateString} to {convertedDate.Kind} time {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
Module Example
   Public Sub Main()
      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 dateStr In dateStrings
         Dim convertedDate As Date = Date.Parse(dateStr)
         Console.WriteLine($"Converted {dateStr} to {convertedDate.Kind} time {convertedDate}")
      Next 
   End Sub
End Module
' 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: {roundtripDate} {roundtripDate.Kind} time.");

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

for formattedDate in formattedDates do
    printfn $"{formattedDate}"
    let roundtripDate = DateTime.Parse(formattedDate, null, DateTimeStyles.RoundtripKind)
    printfn $"   With RoundtripKind flag: {roundtripDate} {roundtripDate.Kind} time."

    let noRoundtripDate = DateTime.Parse(formattedDate, null, DateTimeStyles.None)
    printfn $"   Without RoundtripKind flag: {noRoundtripDate} {noRoundtripDate.Kind} time."

// 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.
Dim 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" }
For Each formattedDate In formattedDates
   Console.WriteLine(formattedDate)
   Dim roundtripDate = DateTime.Parse(formattedDate, Nothing,  
                                      DateTimeStyles.RoundtripKind)                        
   Console.WriteLine($"   With RoundtripKind flag: {roundtripDate} {roundtripDate.Kind} time.")                                          
   Dim noRoundtripDate = DateTime.Parse(formattedDate, Nothing,                                                                                                  DateTimeStyles.None)
   Console.WriteLine($"   Without RoundtripKind flag: {noRoundtripDate} {noRoundtripDate.Kind} time.")
Next         
' 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.

Parse(String)

Source:
DateTime.cs
Source:
DateTime.cs
Source:
DateTime.cs

Converts the string representation of a date and time to its DateTime equivalent by using the conventions of the current culture.

public:
 static DateTime Parse(System::String ^ s);
public static DateTime Parse (string s);
static member Parse : string -> DateTime
Public Shared Function Parse (s As String) As DateTime

Parameters

s
String

A string that contains a date and time to convert. See The string to parse for more information.

Returns

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

Exceptions

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

Examples

The following example parses the string representation of several date and time values by:

  • Using the default format provider, which provides the formatting conventions of the current culture of the computer used to produce the example output. The output from this example reflects the formatting conventions of the en-US culture.

  • Using the default style value, which is AllowWhiteSpaces.

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 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.
open System
open System.Globalization

[<EntryPoint>]
let 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
    let dateString = "2/16/2008 12:15:12 PM"
    try
        let dateValue = DateTime.Parse dateString
        printfn $"'{dateString}' converted to {dateValue}."
    with :? FormatException ->
        printfn $"Unable to convert '{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.
    let dateString = "16/02/2008 12:15:12"
    try
        let dateValue = DateTime.Parse dateString
        printfn $"'{dateString}' converted to {dateValue}."
    with :? 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
        let dateValue = DateTime.Parse(dateString, CultureInfo("fr-FR", false))
        printfn $"'{dateString}' converted to {dateValue}."
    with :? FormatException ->
        printfn $"Unable to convert '{dateString}'."

    // Parse string with date but no time component.
    let dateString = "2/16/2008"
    try
        let dateValue = DateTime.Parse dateString
        printfn $"'{dateString}' converted to {dateValue}."
    with :? FormatException ->
        printfn $"Unable to convert '{dateString}'."

    0

// 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.
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.

Remarks

If s contains time zone information, this method returns a DateTime value whose Kind property is DateTimeKind.Local and converts the date and time in s to local time. Otherwise, it performs no time zone conversion and returns a DateTime value whose Kind property is DateTimeKind.Unspecified.

This overload attempts to parse s by using the formatting conventions of the current culture. The current culture is indicated by the CurrentCulture property. To parse a string using the formatting conventions of a specific culture, call the Parse(String, IFormatProvider) or the Parse(String, IFormatProvider, DateTimeStyles) overloads.

This overload attempts to parse s by using DateTimeStyles.AllowWhiteSpaces style.

See also

Applies to

Parse(ReadOnlySpan<Char>, IFormatProvider)

Source:
DateTime.cs
Source:
DateTime.cs
Source:
DateTime.cs

Parses a span of characters into a value.

public:
 static DateTime Parse(ReadOnlySpan<char> s, IFormatProvider ^ provider) = ISpanParsable<DateTime>::Parse;
public static DateTime Parse (ReadOnlySpan<char> s, IFormatProvider? provider);
static member Parse : ReadOnlySpan<char> * IFormatProvider -> DateTime
Public Shared Function Parse (s As ReadOnlySpan(Of Char), provider As IFormatProvider) As DateTime

Parameters

s
ReadOnlySpan<Char>

The span of characters to parse.

provider
IFormatProvider

An object that provides culture-specific formatting information about s.

Returns

The result of parsing s.

Implements

Applies to

Parse(String, IFormatProvider)

Source:
DateTime.cs
Source:
DateTime.cs
Source:
DateTime.cs

Converts the string representation of a date and time to its DateTime equivalent by using culture-specific format information.

public:
 static DateTime Parse(System::String ^ s, IFormatProvider ^ provider);
public:
 static DateTime Parse(System::String ^ s, IFormatProvider ^ provider) = IParsable<DateTime>::Parse;
public static DateTime Parse (string s, IFormatProvider provider);
public static DateTime Parse (string s, IFormatProvider? provider);
static member Parse : string * IFormatProvider -> DateTime
Public Shared Function Parse (s As String, provider As IFormatProvider) As DateTime

Parameters

s
String

A string that contains a date and time to convert. See The string to parse for more information.

provider
IFormatProvider

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

Returns

An object that is equivalent to the date and time contained in s as specified by provider.

Implements

Exceptions

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

Examples

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.
open System
open System.Globalization

// Define cultures to be used to parse dates.
let cultures = 
    [ CultureInfo.CreateSpecificCulture "en-US"
      CultureInfo.CreateSpecificCulture "fr-FR"
      CultureInfo.CreateSpecificCulture "de-DE" ]

// Define string representations of a date to be parsed.
let dateStrings = 
    [ "01/10/2009 7:34 PM"
      "10.01.2009 19:34"
      "10-1-2009 19:34" ]

// Parse dates using each culture.
for culture in cultures do
    printfn $"Attempted conversions using {culture.Name} culture."
    for dateString in dateStrings do
        try
            let dateValue = DateTime.Parse(dateString, culture)
            printfn $"""   Converted '{dateString}' to {dateValue.ToString("f", culture)}."""
        with :? FormatException ->
            printfn $"   Unable to convert '{dateString}' for culture {culture.Name}." 
    printfn ""


// 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.
Imports System.Globalization

Module ParseDate
   Public Sub Main()
      ' Define cultures to be used to parse dates.
      Dim cultures() As CultureInfo = {CultureInfo.CreateSpecificCulture("en-US"), _
                                       CultureInfo.CreateSpecificCulture("fr-FR"), _
                                       CultureInfo.CreateSpecificCulture("de-DE")}
      ' Define string representations of a date to be parsed.
      Dim dateStrings() As String = {"01/10/2009 7:34 PM", _
                                     "10.01.2009 19:34", _
                                     "10-1-2009 19:34" }
      ' Parse dates using each culture.
      For Each culture In cultures
         Dim dateValue As Date
         Console.WriteLine("Attempted conversions using {0} culture.", culture.Name)
         For Each dateString As String In dateStrings
            Try
               dateValue = Date.Parse(dateString, culture)
               Console.WriteLine("   Converted '{0}' to {1}.", _
                                 dateString, dateValue.ToString("f", culture))
            Catch e As FormatException
               Console.WriteLine("   Unable to convert '{0}' for culture {1}.", _
                                 dateString, culture.Name)
            End Try                                                
         Next
         Console.WriteLine()
      Next                                                                                     
   End Sub
End Module
' 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.

Remarks

If s contains time zone information, this method returns a DateTime value whose Kind property is DateTimeKind.Local and converts the date and time in s to local time. Otherwise, it performs no time zone conversion and returns a DateTime value whose Kind property is DateTimeKind.Unspecified.

This overload attempts to parse s by using the DateTimeStyles.AllowWhiteSpaces style.

See also

Applies to

Parse(ReadOnlySpan<Char>, IFormatProvider, DateTimeStyles)

Source:
DateTime.cs
Source:
DateTime.cs
Source:
DateTime.cs

Converts a memory span that contains string representation of a date and time to its DateTime equivalent by using culture-specific format information and a formatting style.

public static DateTime Parse (ReadOnlySpan<char> s, IFormatProvider? provider = default, System.Globalization.DateTimeStyles styles = System.Globalization.DateTimeStyles.None);
public static DateTime Parse (ReadOnlySpan<char> s, IFormatProvider provider = default, System.Globalization.DateTimeStyles styles = System.Globalization.DateTimeStyles.None);
static member Parse : ReadOnlySpan<char> * IFormatProvider * System.Globalization.DateTimeStyles -> DateTime
Public Shared Function Parse (s As ReadOnlySpan(Of Char), Optional provider As IFormatProvider = Nothing, Optional styles As DateTimeStyles = System.Globalization.DateTimeStyles.None) As DateTime

Parameters

s
ReadOnlySpan<Char>

The memory span that contains the string to parse. See The string to parse for more information.

provider
IFormatProvider

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

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 None.

Returns

An object that is equivalent to the date and time contained in s, as specified by provider and styles.

Exceptions

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

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

Applies to

Parse(String, IFormatProvider, DateTimeStyles)

Source:
DateTime.cs
Source:
DateTime.cs
Source:
DateTime.cs

Converts the string representation of a date and time to its DateTime equivalent by using culture-specific format information and a formatting style.

public:
 static DateTime Parse(System::String ^ s, IFormatProvider ^ provider, System::Globalization::DateTimeStyles styles);
public static DateTime Parse (string s, IFormatProvider provider, System.Globalization.DateTimeStyles styles);
public static DateTime Parse (string s, IFormatProvider? provider, System.Globalization.DateTimeStyles styles);
static member Parse : string * IFormatProvider * System.Globalization.DateTimeStyles -> DateTime
Public Shared Function Parse (s As String, provider As IFormatProvider, styles As DateTimeStyles) As DateTime

Parameters

s
String

A string that contains a date and time to convert. See The string to parse for more information.

provider
IFormatProvider

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

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 None.

Returns

An object that is equivalent to the date and time contained in s, as specified by provider and styles.

Exceptions

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

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

Examples

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.
open System
open System.Globalization

[<EntryPoint>]
let main _ =
    // Parse a date and time with no styles.
    let dateString = "03/01/2009 10:00 AM"
    let culture = CultureInfo.CreateSpecificCulture "en-US"
    let styles = DateTimeStyles.None
    try
        let result = DateTime.Parse(dateString, culture, styles)
        printfn $"{dateString} converted to {result} {result.Kind}."
    with :? FormatException ->
        printfn $"Unable to convert {dateString} to a date and time."

    // Parse the same date and time with the AssumeLocal style.
    let styles = DateTimeStyles.AssumeLocal
    try
        let result = DateTime.Parse(dateString, culture, styles)
        printfn $"{dateString} converted to {result} {result.Kind}."
    with :? FormatException ->
        printfn $"Unable to convert {dateString} to a date and time."

    // 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.
    let dateString = "2009/03/01T10:00:00-5:00"
    let styles = DateTimeStyles.AssumeLocal
    try
        let result = DateTime.Parse(dateString, culture, styles)
        printfn $"{dateString} converted to {result} {result.Kind}."
    with :? FormatException ->
        printfn $"Unable to convert {dateString} to a date and time."

    // Attempt to convert a string in improper ISO 8601 format.
    let dateString = "03/01/2009T10:00:00-5:00"
    try
        let result = DateTime.Parse(dateString, culture, styles)
        printfn $"{dateString} converted to {result} {result.Kind}."
    with :? FormatException ->
        printfn $"Unable to convert {dateString} to a date and time."

    // Assume a date and time string formatted for the fr-FR culture is the local
    // time and convert it to UTC.
    let dateString = "2008-03-01 10:00"
    let culture = CultureInfo.CreateSpecificCulture "fr-FR"
    let styles = DateTimeStyles.AdjustToUniversal ||| DateTimeStyles.AssumeLocal
    try
        let result = DateTime.Parse(dateString, culture, styles)
        printfn $"{dateString} converted to {result} {result.Kind}."
    with :? FormatException ->
        printfn $"Unable to convert {dateString} to a date and time."

    0

// 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.
Imports System.Globalization

Module ParseDateExample
   Public Sub Main()
      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)
         Console.WriteLine("{0} converted to {1} {2}.", _
                           dateString, result, result.Kind.ToString())
      Catch e As FormatException
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString)
      End Try      
      
      ' 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 e As FormatException
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString)
      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)
         Console.WriteLine("{0} converted to {1} {2}.", _
                           dateString, result, result.Kind.ToString())
      Catch e As FormatException
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString)
      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)
         Console.WriteLine("{0} converted to {1} {2}.", _
                           dateString, result, result.Kind.ToString())
      Catch e As FormatException
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString)
      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)
         Console.WriteLine("{0} converted to {1} {2}.", _
                           dateString, result, result.Kind.ToString())
      Catch e As FormatException
         Console.WriteLine("Unable to convert {0} to a date and time.", dateString)
      End Try      
   End Sub
End Module
'
' 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.

Remarks

This method overload converts the date and time in s and sets the Kind property of the returned DateTime value as follows:

If Time zone conversion Kind property
s contains no time zone information. None. DateTimeKind.Unspecified
s contains time zone information. To the time in the local time zone DateTimeKind.Local
s contains time zone information, and styles includes the DateTimeStyles.AdjustToUniversal flag. To Coordinated Universal Time (UTC) DateTimeKind.Utc
s contains the Z or GMT time zone designator, and styles includes the DateTimeStyles.RoundtripKind. None. DateTimeKind.Utc

See also

Applies to