Επεξεργασία

Κοινή χρήση μέσω


Parse date and time strings in .NET

Parsing strings to convert them to DateTime objects requires you to specify information about how the dates and times are represented as text. Different cultures use different orders for day, month, and year. Some time representations use a 24-hour clock, others specify "AM" and "PM." Some applications need only the date. Others need only the time. Still others need to specify both the date and time. The methods that convert strings to DateTime objects enable you to provide detailed information about the formats you expect and the elements of a date and time your application needs. There are three subtasks to correctly converting text into a DateTime:

  1. You must specify the expected format of the text representing a date and time.
  2. You can specify the culture for the format of a date time.
  3. You can specify how missing components in the text representation are set in the date and time.

The Parse and TryParse methods convert many common representations of a date and time. The ParseExact and TryParseExact methods convert a string representation that conforms to the pattern specified by a date and time format string. For more information, see the articles on standard date and time format strings and custom date and time format strings.

The current DateTimeFormatInfo object provides more control over how text should be interpreted as a date and time. Properties of a DateTimeFormatInfo describe the date and time separators, the names of months, days, and eras, and the format for the "AM" and "PM" designations. The CultureInfo returned by CultureInfo.CurrentCulture has a CultureInfo.DateTimeFormat property that represents the current culture. If you want a specific culture or custom settings, you specify the IFormatProvider parameter of a parsing method. For the IFormatProvider parameter, specify a CultureInfo object, which represents a culture, or a DateTimeFormatInfo object.

The text representing a date or time might be missing some information. For example, most people would assume the date "March 12" represents the current year. Similarly, "March 2018" represents the month of March in the year 2018. Text representing time often does only include hours, minutes, and an AM/PM designation. Parsing methods handle this missing information by using reasonable defaults:

  • When only the time is present, the date portion uses the current date.
  • When only the date is present, the time portion is midnight.
  • When the year isn't specified in a date, the current year is used.
  • When the day of the month isn't specified, the first day of the month is used.

If the date is present in the string, it must include the month and one of the day or year. If the time is present, it must include the hour, and either the minutes or the AM/PM designator.

You can specify the NoCurrentDateDefault constant to override these defaults. When you use that constant, any missing year, month, or day properties are set to the value 1. The last example using Parse demonstrates this behavior.

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 DateTimeKind.Local. Its value is also adjusted to the local time zone of your machine. You can modify this behavior by using a DateTimeStyles value with the parsing method.

The format provider is also used to interpret an ambiguous numeric date. It's unclear which components of the date represented by the string "02/03/04" are the month, day, and year. The components are interpreted according to the order of similar date formats in the format provider.

Parse

The following example illustrates the use of the DateTime.Parse method to convert a string into a DateTime. This example uses the culture associated with the current thread. If the CultureInfo associated with the current culture can't parse the input string, a FormatException is thrown.

Tip

All the C# samples in this article run in your browser. Press the Run button to see the output. You can also edit them to experiment yourself.

Note

These examples are available in the GitHub docs repo for both C# and Visual Basic.

string dateInput = "Jan 1, 2009";
var parsedDate = DateTime.Parse(dateInput);
Console.WriteLine(parsedDate);
// Displays the following output on a system whose culture is en-US:
//       1/1/2009 00:00:00
Dim MyString As String = "Jan 1, 2009"
Dim MyDateTime As DateTime = DateTime.Parse(MyString)
Console.WriteLine(MyDateTime)
' Displays the following output on a system whose culture is en-US:
'       1/1/2009 00:00:00

You can also explicitly define the culture whose formatting conventions are used when you parse a string. You specify one of the standard DateTimeFormatInfo objects returned by the CultureInfo.DateTimeFormat property. The following example uses a format provider to parse a German string into a DateTime. It creates a CultureInfo representing the de-DE culture. That CultureInfo object ensures successful parsing of this particular string. This process precludes whatever setting is in the CurrentCulture of the CurrentThread.

var cultureInfo = new CultureInfo("de-DE");
string dateString = "12 Juni 2008";
var dateTime = DateTime.Parse(dateString, cultureInfo);
Console.WriteLine(dateTime);
// The example displays the following output:
//       6/12/2008 00:00:00
Dim MyCultureInfo As New CultureInfo("de-DE")
Dim MyString As String = "12 Juni 2008"
Dim MyDateTime As DateTime = DateTime.Parse(MyString, MyCultureInfo)
Console.WriteLine(MyDateTime)
' The example displays the following output:
'       6/12/2008 00:00:00

However, you can use overloads of the Parse method to specify custom format providers. The Parse method doesn't support parsing non-standard formats. To parse a date and time expressed in a non-standard format, use the ParseExact method instead.

The following example uses the DateTimeStyles enumeration to specify that the current date and time information shouldn't be added to the DateTime for unspecified fields.

var cultureInfo = new CultureInfo("de-DE");
string dateString = "12 Juni 2008";
var dateTime = DateTime.Parse(dateString, cultureInfo,
                                DateTimeStyles.NoCurrentDateDefault);
Console.WriteLine(dateTime);
// The example displays the following output if the current culture is en-US:
//      6/12/2008 00:00:00
Dim MyCultureInfo As New CultureInfo("de-DE")
Dim MyString As String = "12 Juni 2008"
Dim MyDateTime As DateTime = DateTime.Parse(MyString, MyCultureInfo,
                           DateTimeStyles.NoCurrentDateDefault)
Console.WriteLine(MyDateTime)
' The example displays the following output if the current culture is en-US:
'       6/12/2008 00:00:00

ParseExact

The DateTime.ParseExact method converts a string to a DateTime object if it conforms to one of the specified string patterns. When a string that isn't one of the forms specified is passed to this method, a FormatException is thrown. You can specify one of the standard date and time format specifiers or a combination of the custom format specifiers. Using the custom format specifiers, it's possible for you to construct a custom recognition string. For an explanation of the specifiers, see the articles on standard date and time format strings and custom date and time format strings.

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

var cultureInfo = new CultureInfo("en-US");
string[] dateStrings = { " Friday, April 10, 2009", "Friday, April 10, 2009" };
foreach (string dateString in dateStrings)
{
    try
    {
        var dateTime = DateTime.ParseExact(dateString, "D", cultureInfo);
        Console.WriteLine(dateTime);
    }
    catch (FormatException)
    {
        Console.WriteLine("Unable to parse '{0}'", dateString);
    }
}
// The example displays the following output:
//       Unable to parse ' Friday, April 10, 2009'
//       4/10/2009 00:00:00
Dim MyCultureInfo As 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)
        Console.WriteLine(MyDateTime)
    Catch e As FormatException
        Console.WriteLine("Unable to parse '{0}'", dateString)
    End Try
Next
' The example displays the following output:
'       Unable to parse ' Friday, April 10, 2009'
'       4/10/2009 00:00:00

Each overload of the Parse and ParseExact methods also has an IFormatProvider parameter that provides culture-specific information about the formatting of the string. The IFormatProvider object is a CultureInfo object that represents a standard culture or a DateTimeFormatInfo object that is returned by the CultureInfo.DateTimeFormat property. ParseExact also uses an additional string or string array argument that defines one or more custom date and time formats.

See also