Compartir a través de


Parsing Date and Time Strings

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Parsing methods convert the string representation of a date and time to an equivalent DateTime or DateTimeOffset object. The DateTime.Parse, DateTime.TryParse, DateTimeOffset.Parse, and DateTimeOffset.TryParse methods convert any of several common representations of a date and time. The ParseExact, TryParseExact, DateTimeOffset.ParseExact, and DateTime.TryParseExact methods convert a string representation that conforms to the pattern specified by either a standard date and time format string or a custom date and time format string.

Parsing is influenced by the properties of a format provider that supplies information such as the strings used for date and time separators, and the names of months, days, and eras. The format provider is the current DateTimeFormatInfo object, which is provided implicitly by the current thread culture or explicitly by the IFormatProvider parameter of a parsing method. For the IFormatProvider parameter, specify a CultureInfo object, which represents a culture, or a DateTimeFormatInfo object.

The string representation of a date to be parsed must include the month and at least a day or year. The string representation of a time must include the hour and at least minutes or the AM/PM designator. However, parsing supplies default values for omitted components if possible. A missing date defaults to the current date, a missing year defaults to the current year, a missing day of the month defaults to the first day of the month, and a missing time defaults to midnight.

If the string representation specifies only a time, parsing returns a DateTime object with its Year, Month, and Day properties set to the corresponding values of the Today property. However, if the NoCurrentDateDefault constant is specified in the parsing method, the resulting year, month, and day properties are set to the value 1.

In addition to a date and a time component, the string representation of a date and time can include an offset that indicates how much the time differs from Coordinated Universal Time (UTC). For example, the string "2/14/2007 5:32:00 -7:00" defines a time that is seven hours earlier than UTC. If an offset is omitted from the string representation of a time, parsing returns a DateTime object with its Kind property set to DateTimeKind.Unspecified. If an offset is specified, parsing returns a DateTime object with its Kind property set to Local and its value adjusted to the local time zone of your machine. You can modify this behavior by using a DateTimeStyles constant with the parsing method.

The format provider is also used to interpret an ambiguous numeric date. For example, it is not clear which components of the date represented by the string "02/03/04" are the month, day, and year. In this case, the components are interpreted according to the order of similar date formats in the format provider.

Parse

The following code example illustrates the use of the Parse(String) method to convert a string into a DateTime. This example uses the culture associated with the current thread to perform the parse. If the CultureInfo object associated with the current culture cannot parse the input string, a FormatException is thrown.

Dim MyString As String = "Jan 1, 2009"
Dim MyDateTime As DateTime = DateTime.Parse(MyString)
outputBlock.Text += MyDateTime & vbCrLf
' Displays the following output on a system whose culture is en-US:
'       1/1/2009 12:00:00 AM
string MyString = "Jan 1, 2009";
DateTime MyDateTime = DateTime.Parse(MyString);
outputBlock.Text += MyDateTime + "\n";
// Displays the following output on a system whose culture is en-US:
//       1/1/2009 12:00:00 AM

You can also specify a CultureInfo object set to one of the cultures defined by that object, or you can specify one of the standard DateTimeFormatInfo objects returned by the CultureInfo.DateTimeFormat property. In this case, the culture associated with the current thread is not used in the parsing operation. The following example uses a format provider to parse a German string into a DateTime value. A CultureInfo object representing the de-DE culture is defined and passed with the string being parsed to ensure successful parsing of this particular string.

Imports System.Globalization

Module Example
   Public Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)
      Dim MyCultureInfo As CultureInfo = New CultureInfo("de-DE")
      Dim MyString As String = "12 Juni 2008"
      Dim MyDateTime As DateTime = DateTime.Parse(MyString, MyCultureInfo)
      outputBlock.Text &= MyDateTime & vbCrLf
   End Sub
End Module
' The example displays the following output:
'       6/12/2008 12:00:00 AM
using System;
using System.Globalization;

public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      CultureInfo MyCultureInfo = new CultureInfo("de-DE");
      string MyString = "12 Juni 2008";
      DateTime MyDateTime = DateTime.Parse(MyString, MyCultureInfo);
      outputBlock.Text += MyDateTime + "\n";
   }
}
// The example displays the following output:
//       6/12/2008 12:00:00 AM

However, although you can use overloads of the Parse method to specify custom format providers, the method does not support the use of non-standard format providers. To parse a date and time expressed in a non-standard format, use the ParseExact method instead.

The following code example uses the DateTimeStyles enumeration to specify that the current date and time information should not be added to the DateTime for fields that the string does not define.

Imports System.Globalization

Module Example
   Public Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)
      Dim MyCultureInfo As CultureInfo = New CultureInfo("de-DE")
      Dim MyString As String = "12 Juni 2008"
      Dim MyDateTime As DateTime = DateTime.Parse(MyString, MyCultureInfo, _
                                   DateTimeStyles.NoCurrentDateDefault)
      outputBlock.Text &= MyDateTime & vbCrLf
   End Sub
End Module
' The example displays the following output if the current culture is en-US:
'       6/12/2008 12:00:00 AM
using System;
using System.Globalization;

public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      CultureInfo MyCultureInfo = new CultureInfo("de-DE");
      string MyString = "12 Juni 2008";
      DateTime MyDateTime = DateTime.Parse(MyString, MyCultureInfo,
                                           DateTimeStyles.NoCurrentDateDefault);
      outputBlock.Text += MyDateTime + "\n";
   }
}
// The example displays the following output if the current culture is en-US:
//      6/12/2008 12:00:00 AM

ParseExact

The DateTime.ParseExact method converts a string that conforms to a specified string pattern to a DateTime object. When a string that is not of the form specified is passed to this method, a FormatException is thrown. You can specify one of the standard date and time format specifiers or a limited combination of the custom date and time format specifiers. Using the custom format specifiers, it is possible for you to construct a custom recognition string. For an explanation of the specifiers, see Standard Date and Time Format Strings and Custom Date and Time Format Strings.

Each overload of the ParseExact method also has an IFormatProvider parameter that typically provides culture-specific information about the formatting of the string. Typically, this IFormatProvider object is a CultureInfo object that represents a standard culture or a DateTimeFormatInfo object that is returned by the CultureInfo.DateTimeFormat property. However, unlike the other date and time parsing functions, this method also supports an IFormatProvider that defines a non-standard date and time format.

In the following example, the DateTime.ParseExact(String, String, IFormatProvider) method is passed a string object to parse, followed by a format specifier, followed by a CultureInfo object representing the en-US culture. This ParseExact(String, String, IFormatProvider) method can only parse strings that exhibit the long date pattern in the en-US culture.

Imports System.Globalization

Module Example
   Public Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)
      Dim MyCultureInfo As CultureInfo = New CultureInfo("en-US")
      Dim MyString() As String = {" Friday, April 10, 2009", "Friday, April 10, 2009"}
      For Each dateString As String In MyString
         Try
            Dim MyDateTime As DateTime = DateTime.ParseExact(dateString, "D", _
                                                             MyCultureInfo)
            outputBlock.Text &= MyDateTime & vbCrLf
         Catch e As FormatException
            outputBlock.Text += String.Format("Unable to parse '{0}'", dateString) & vbCrLf
         End Try
      Next
   End Sub
End Module
' The example displays the following output:
'       Unable to parse ' Friday, April 10, 2009'
'       4/10/2009 12:00:00 AM
using System;
using System.Globalization;

public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      CultureInfo MyCultureInfo = new CultureInfo("en-US");
      string[] MyString = { " Friday, April 10, 2009", "Friday, April 10, 2009" };
      foreach (string dateString in MyString)
      {
         try
         {
            DateTime MyDateTime = DateTime.ParseExact(dateString, "D", MyCultureInfo);
            outputBlock.Text += MyDateTime + "\n";
         }
         catch (FormatException)
         {
            outputBlock.Text += String.Format("Unable to parse '{0}'", dateString) + "\n";
         }
      }
   }
}
// The example displays the following output:
//       Unable to parse ' Friday, April 10, 2009'
//       4/10/2009 12:00:00 AM