Convert strings to DateTime - .NET (2024)

  • Article

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 TryNext' 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

  • Parsing strings
  • Formatting types
  • Type conversion in .NET
  • Standard date and time formats
  • Custom date and time format strings
Convert strings to DateTime - .NET (2024)

FAQs

How to convert string to valid DateTime in C#? ›

TryParseExact() Method

The last method to help us convert the string to DateTime in C# is TryParseExact(). It converts the specified string to equivalent DateTime with a specified format and culture. The string value of the format must match the string value of DateTime.

How do you convert a string to a DateTime? ›

In Python, we can use the datetime. strptime() method to convert a string to a datetime object. The strptime() method takes two arguments: the string to be converted and a format string specifying the input string's format.

How to convert list of strings to DateTime in C#? ›

Parse() and ParseExact() are quite similar. However, in ParseExact(), we can pass format as an extra parameter not available in Parse(). Format parameter helps to convert a string date value to a DateTime object when a date is a different format like "11-23-2015" (Format should be "MM-dd-yyyy").

How to convert DateTime in string in C#? ›

Convert DateTime to String using the ToString() Method

Use the DateTime. ToString() method to convert the date object to string with the local culture format. The value of the DateTime object is formatted using the pattern defined by the DateTimeFormatInfo.

How to convert string to DateTime in .NET Core? ›

ParseExact() method converts the specified string representation of a date and time to its DateTime equivalent. The format of the string representation must match a specified format exactly. string dateInyyyyMMdd = "20220519"; DateTime dateTime; dateTime = DateTime. ParseExact(dateInyyyyMMdd, "yyyyMMdd", CultureInfo.

How to convert empty string to DateTime in C#? ›

ConvertToDateTime(dateString) ' Convert an empty string. dateString = String. Empty ConvertToDateTime(dateString) ' Convert a non-date string.

How do you convert a string column to DateTime? ›

Below are the methods ways by which we can convert type from string to datetime format in Pandas Dataframe:
  1. Using pd. to_datetime() function.
  2. Using DataFrame. astype() function.
  3. Using pandas. to_datetime()
Jul 11, 2024

How to create a new DateTime in C#? ›

Working with Date and Time in C#
  1. DateTime newDate = new DateTime(year, month, day); DateTime newDate = new DateTime(year, month, day, hour, munite, second);
  2. DateTime currentDateTime = DateTime.Now; //returns current date and time. ...
  3. // Calculate age with TimeSpan struct.
Aug 30, 2020

How to convert timestamp from string to DateTime? ›

Here are different methods to convert timestamp strings to datetime objects.
  1. Using strptime()
  2. Using datetime.strptime()
  3. Using dateutil.parser.parse()
  4. Using datetime.from timestamp()
Aug 28, 2023

How to convert list to string in C# net? ›

Join(String. Empty, myList. ToArray()); This will implicitly call the ToString() method on each of the items in the list and concatenate them.

How to convert string to DateTime with milliseconds in C#? ›

If you're working with the string representation of a date, convert it to a DateTime or a DateTimeOffset value by using the static DateTime. Parse(String) or DateTimeOffset. Parse(String) method. To extract the string representation of a time's millisecond component, call the date and time value's DateTime.

How to convert string to short date in C#? ›

ToShortDateString() Method in C# This method is used to convert the value of the current DateTime object to its equivalent short date string representation. Syntax: public string ToShortDateString ();

What is the ToString format for DateTime in C#? ›

ToString("MM-dd-yyyy HH:mm:ss")); In this example, we're using the ToString method with a pattern like "MM-dd-yyyy HH:mm:ss". This pattern instructs C# to display the DateTime as month, day, year, hour, minute, and second, separated by dashes and colons.

What is the difference between parse and ParseExact? ›

Parse : Useful when the date and time strings come from sources that use the same format as the current culture. ParseExact : Useful when dealing with date and time strings from fixed-format sources (like certain logs, databases, or systems) where you know the exact format beforehand.

How to convert date only to DateTime in C#? ›

We can convert DateOnly Objects to DateTime by using: var dateTime = dateOnly. ToDateTime(TimeOnly. MinValue);

How to format a string date time in C#? ›

C# DateTime Format
FormatResult
DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK")2015-05-16T05:50:06.7199222-04:00
DateTime.Now.ToString("ddd, dd MMM yyy HH':'mm':'ss 'GMT'")Fri, 16 May 2015 05:50:06 GMT
DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss")2015-05-16T05:50:06
19 more rows
Oct 4, 2023

How to convert string to timestamp in C? ›

The strptime() function converts the character string pointed to by buf to values that are stored in the tm structure pointed to by tm, using the format specified by format. The format contains zero or more directives.

How to get only date from string in C#? ›

ToString() − One more way to get the date from DateTime is using ToString() extension method. The advantage of using ToString() extension method is that we can specify the format of the date that we want to fetch. DateTime. Date − will also remove the time from the DateTime and provides us the Date only.

How to validate date format using regular expression in C#? ›

Common Regular Expressions for Date Formatting

"\d{2}/\d{2}/\d{4}" - Matches dates in the format month/day/year, such as "01/24/2022". "\d{4}-\d{2}-\d{2}" - Matches dates in the format year-month-day, such as "2022-01-24". "\d{2}-\d{2}-\d{4}" - Matches dates in the format day-month-year, such as "24-01-2022".

Top Articles
Latest Posts
Article information

Author: Otha Schamberger

Last Updated:

Views: 5369

Rating: 4.4 / 5 (75 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Otha Schamberger

Birthday: 1999-08-15

Address: Suite 490 606 Hammes Ferry, Carterhaven, IL 62290

Phone: +8557035444877

Job: Forward IT Agent

Hobby: Fishing, Flying, Jewelry making, Digital arts, Sand art, Parkour, tabletop games

Introduction: My name is Otha Schamberger, I am a vast, good, healthy, cheerful, energetic, gorgeous, magnificent person who loves writing and wants to share my knowledge and understanding with you.