Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit editor mode

Parse date and time strings in .NET

Feedback

In this article

Parsing strings to convert them toDateTime 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 toDateTime 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 aDateTime:

  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.

TheParse andTryParse methods convert many common representations of a date and time. TheParseExact andTryParseExact methods convert a string representation that conforms to the pattern specified by a date and time format string. For more information, see the articles onstandard date and time format strings andcustom date and time format strings.

The currentDateTimeFormatInfo object provides more control over how text should be interpreted as a date and time. Properties of aDateTimeFormatInfo describe the date and time separators, the names of months, days, and eras, and the format for the "AM" and "PM" designations. TheCultureInfo returned byCultureInfo.CurrentCulture has aCultureInfo.DateTimeFormat property that represents the current culture. If you want a specific culture or custom settings, you specify theIFormatProvider parameter of a parsing method. For theIFormatProvider parameter, specify aCultureInfo object, which represents a culture, or aDateTimeFormatInfo 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 theNoCurrentDateDefault constant to override these defaults. When you use that constant, any missing year, month, or day properties are set to the value1. Thelast example usingParse 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 aDateTime object with itsKind property set toDateTimeKind.Unspecified. If an offset is specified, parsing returns aDateTime object with itsKind property set toDateTimeKind.Local. Its value is also adjusted to the local time zone of your machine. You can modify this behavior by using aDateTimeStyles 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 theDateTime.Parse method to convert astring into aDateTime. This example uses the culture associated with the current thread. If theCultureInfo associated with the current culture can't parse the input string, aFormatException is thrown.

Tip

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

Note

These examples are available in the GitHub docs repo for bothC# andVisual 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 standardDateTimeFormatInfo objects returned by theCultureInfo.DateTimeFormat property. The following example uses a format provider to parse a German string into aDateTime. It creates aCultureInfo representing thede-DE culture. ThatCultureInfo object ensures successful parsing of this particular string. This process precludes whatever setting is in theCurrentCulture of theCurrentThread.

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 theParse method to specify custom format providers. TheParse method doesn't support parsing non-standard formats. To parse a date and time expressed in a non-standard format, use theParseExact method instead.

The following example uses theDateTimeStyles enumeration to specify that the current date and time information shouldn't be added to theDateTime 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

TheDateTime.ParseExact method converts a string to aDateTime 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, aFormatException 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 onstandard date and time format strings andcustom date and time format strings.

In the following example, theDateTime.ParseExact method is passed a string object to parse, followed by a format specifier, followed by aCultureInfo object. ThisParseExact method can only parse strings that follow the long date pattern in theen-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 '{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 TryNext' The example displays the following output:'       Unable to parse ' Friday, April 10, 2009''       4/10/2009 00:00:00

Each overload of theParse andParseExact methods also has anIFormatProvider parameter that provides culture-specific information about the formatting of the string. TheIFormatProvider object is aCultureInfo object that represents a standard culture or aDateTimeFormatInfo object that is returned by theCultureInfo.DateTimeFormat property.ParseExact also uses an additional string or string array argument that defines one or more custom date and time formats.

See also

Collaborate with us on GitHub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, seeour contributor guide.

Feedback

Was this page helpful?

YesNoNo

Need help with this topic?

Want to try using Ask Learn to clarify or guide you through this topic?

Suggest a fix?

  • Last updated on

In this article

Was this page helpful?

YesNo
NoNeed help with this topic?

Want to try using Ask Learn to clarify or guide you through this topic?

Suggest a fix?