String To DateTime Conversion In C# (2024)

C# DateTime Conversion

C# DateTime is a struct type mostly used in applications to manage date, date-time, and time data types. Most of the time, we get a date in the form of a string, and we usually need to parse to a DateTime object to perform some operations like date difference, weekday, month name, formatting, and so on. For instance, there is a string value ("12/10/2015"), and we require to find out the weekdays (Sunday or Monday..) of the date. In this scenario, we need to convert a string value to a DateTime object and then use the WeekDay property(obj.WeekDay) to determine the weekday. We can accomplish the same by built-in methods like Convert.ToDateTime(), DateTime.Parse(), DateTime.ParseExact(), DateTime.TryParse(), and DateTime.TryParseExact().

You can learn more about DateTime in C# here.

Now, why do we have so many methods to parse a string to a DateTime object? Is it really necessary? If yes, then in which scenario do we need to use them? We will discuss how all these DateTime conversion methods are used and what the differences are between them.

Let's start

Convert.ToDateTime()

It converts specified string data to equivalent date and time. It is available in System (mscorlib.dll) namespace and introduced .NET framework 2.0 onwards. It contains a couple of overload methods, but two are the most important:

ToDateTime(string value)

Here value is a string representation of date and time. For instance, Convert.DateTime(“1/1/2010”)

ToDateTime(string value, IFormatProvider provider)

  • Value.It is a string representation of date and time.
  • Provider.It is an object which provides culture-specific info.
CultureInfoculture=newCultureInfo("en-US");DateTimetempDate=Convert.ToDateTime("1/1/201012:10:15PM",culture); 

Here "en-US" is cultural information about the United States of America. You can change as per culture, like French, German, etc.

If the string value is not null, then it internally calls DateTime.Parse() to give the result. On the other hand, if a string value is null, then it gives DateTime.MinValue as "1/1/0001 12:00:00 AM". This method always tries to parse the value completely and avoid the FormatException issue.

Let's have a look at the following examples.

//Convert.ToDateTime()stringdateString=null;//Convertanullstring.DateTimedateTime10=Convert.ToDateTime(dateString);//1/1/000112:00:00AMdateString="notadate";//Exception:ThestringwasnotrecognizedasavalidDateTime.// Thereisanunknownwordstartingatindex0.DateTimedateTime11=Convert.ToDateTime(dateString);dateString="TueDec30,2015"; //Exception:StringwasnotrecognizedasavalidDateTimebecausethedayofweekwasincorrect.DateTimedateTime12=Convert.ToDateTime(dateString);

DateTime.Parse()

It converts specified string data to equivalent date and time. It is available in System (mscorlib.dll) namespace and introduced .NET framework 1.1 onwards. It contains the following overload methods:

DateTime.Parse(String value)

  • Value.It is the string representation of date and time. For instance, DateTime.Parse(“01/10/2015”);

DateTime.Parse(String value, IFormatProvider provider)

  • Value.It is a string representation of date and time.
  • Provider.It is an object which provides culture-specific info.

DateTime.Parse(String value, IFormatProvider provider, DateTypeStyles styles)

  • Value.It is a string representation of date and time.
  • Provider.It is an object which provides culture-specific info.
  • Styles.It defines the formatting options that customize string parsing for some date and time parsing methods. For instance, AllowWhiteSpaces is a value that helps ignore all spaces in the string while it parses.

More on this visit ishere.

If the value is null, it returns ArgumentNullException, and in the same way, if the value contains some invalid date format, it returns FormatException.

Here are a couple of examples.

stringdateString=null;// Exception: Argument null exceptionDateTimedateTime10=DateTime.Parse(dateString);dateString="notadate";//Exception:ThestringwasnotrecognizedasavalidDateTime.// Thereisanunknownwordstartingatindex0.DateTimedateTime11=DateTime.Parse(dateString);dateString="TueDec30,2015"; //Exception:StringwasnotrecognizedasavalidDateTimebecausethedayofweekwasincorrect.DateTimedateTime12=DateTime.Parse(dateString);

DateTime.ParseExact()

It converts a specified string to an equivalent DateTime with a specified format and culture. The format's string value must match a string value of datetime. It is available in System (mscorlib.dll) namespace and introduced .NET framework 2.0 onwards. It contains the following overload methods:

DateTime.ParseExact(string value, string format, IFormatProvider provider)

  • Value.It is a string representation of date and time.
  • Format.It is a format specifier that defines what a date looks like after conversion.
  • Provider.It is an object which specifies cultural info.

DateTime.ParseExact(string value, string format, IFormatProvider provider, DateTimeStyles style)

  • Value.It is a string representation of date and time.
  • Format.It is a format specifier that defines what a date looks like after conversion.
  • Provider.It is an object which specifies cultural info.
  • Style.It defines the formatting options that customize string parsing for some date and time parsing methods.

DateTime.ParseExact(string value, string[] formats, IFormatProvider provider, DateTimeStyles style)

  • Value.It is a string representation of date and time.
  • Formats.It is a format specifier that defines what a date looks like after conversion. A string array contains a list of formats; at least one formatmust match the string(value) to convert the DateTime object.
  • Provider.It is an object which specifies cultural info.
  • Style.It defines the formatting options that customize string parsing for some date and time parsing methods.

The format must match with string date time, or it throws FormatException. If the value is null, it returns ArgumentNullException, and in the same way, if the value contains some invalid date format, it returns FormatException. So to overcome this issue, you can use a string format array with some possibilities. Suppose your date may be in a format like "12/12/2015" or "12-12-2015" here; you need to pass a string array with a format like "MM/dd/yyyy" and "MM-dd-yyyy".

Here are a couple of examples that may help you understand it better.

//Convertanullstring.stringdateString=null;CultureInfoprovider=CultureInfo.InvariantCulture;//ItthrowsArgumentnullexceptionDateTimedateTime10=DateTime.ParseExact(dateString,"mm/dd/yyyy",provider);dateString="notadate";//Exception:ThestringwasnotrecognizedasavalidDateTime.Thereisanunknownwordstartingatindex0.DateTimedateTime11=DateTime.ParseExact(dateString,"mm/dd/yyyy",provider);dateString="TueDec30,2015";//Exception:StringwasnotrecognizedasavalidDateTimebecausethedayofweekwasincorrect.DateTimedateTime12=DateTime.ParseExact(dateString,"mm/dd/yyyy",provider);dateString="10-22-2015";//Exception:StringwasnotrecognizedasavalidDateTimebecausethedayofweekwasincorrect.DateTimedateTime13=DateTime.ParseExact(dateString,"MM-dd-yyyy",provider);//10/22/201512:00:00AMstringtemp=dateTime13.ToString();dateString="10-12-2015";//Output:10/22/201512:00:00AMDateTimedateTime16=DateTime.ParseExact(dateString,newstring[]{"MM.dd.yyyy","MM-dd-yyyy","MM/dd/yyyy"},provider,DateTimeStyles.None);

DateTime.TryParse()

It converts specified string data to equivalent datetime and returns the Boolean value after parsing, indicating that parsing has succeeded. It is available in System (mscorlib.dll) namespace and introduced .NET framework 2.0 onwards. It contains the following overload methods:

DateTime.TryParse (String value, out DateTime result)

  • Value.It is a string representation of date and time
  • Result.It holds the DateTime value after parsing.

DateTime.TryParse(String value, IFormatProvider provider, DateTimeStyles styles, out DateTime result)

  • Value.It is a string representation of date and time
  • Provider.It is an object which provides culture-specific info.
  • Styles.It defines the formatting options that customize string parsing for some date and time parsing methods. For instance, AllowWhiteSpaces is a value that helps ignore all spaces in the string while it parses.
  • Result.It holds the DateTime value after parsing.

TryParse() always tries to parse the string value datetime. If the conversion succeeds, it returns the correct DateTime value and MinValue(1/1/0001 12:00:00 AM) if the conversion fails. If the string value is null or empty and you try to convert it to DateTime, then it returns MinValue only. Secondly, it always returns a Boolean value indicating whether the conversion succeeded or failed. If the conversion succeeded, then True otherwise, it returns False.

It is most likely DateTime.Parse(). But the only difference is that it doesn't throw any exception when the conversion fails. Rather, it returns the MinValue of DateTime.

Here are a couple of examples.

stringdateString=null;//Convertanullstring.DateTimedateTime10;boolisSuccess=DateTime.TryParse(dateString,outdateTime10);//1/1/000112:00:00AMdateString="notadate";DateTimedateTime11;boolisSuccess1=DateTime.TryParse(dateString,outdateTime11);//1/1/000112:00:00AMdateString="TueDec30,2015";DateTimedateTime12;boolisSuccess2=DateTime.TryParse(dateString,outdateTime12);//1/1/000112:00:00AM

DateTime.TryParseExact()

It converts a specified string to an equivalent DateTime with a specified format and culture. The format's string value must match a string value of datetime. It is available in System (mscorlib.dll) namespace and introduced .NET framework 2.0 onwards. It contains the following overload methods.

DateTime.ParseExact(string value, string format, IFormatProvider provider, DateTimeStyles style)

  • Value.It is a string representation of date and time.
  • Format.It is a format specifier that defines what a date looks like after conversion.
  • Provider.It is an object which specifies culture info.
  • Style.It defines the formatting options that customize string parsing for some date and time parsing methods.

DateTime.ParseExact(string value, string[] formats, IFormatProvider provider, DateTimeStyles style)

  • Value.It is a string representation of date and time.
  • Formats.It is a format specifier that defines what a date looks like after conversion. A string array contains a list of formats, and at least one format must match the string (value) to convert the DateTime object.
  • Provider.It is an object which specifies cultural info.
  • Style. It defines the formatting options that customize string parsing for some date and time parsing methods.

It returns MinValue( 1/1/0001 12:00:00 AM) if the following condition satisfies:

  • The string value is null.
  • The stringvalue is blank.
  • The stringis not the correct date.
  • The stringis not matched with the format provided.

It throws an exception only if the DateTimeStyle value is not valid; otherwise returns MinValue.

Secondly, it returns a Boolean value (true or false) to indicate whether the conversion succeeded. It returns True if the conversion succeeded and False if the conversion failed.

The following are some examples that will help you to understand it better.

stringdateString=null;CultureInfoprovider=CultureInfo.InvariantCulture;DateTimedateTime10;//1/1/000112:00:00AMboolisSuccess1=DateTime.TryParseExact(dateString,"MM/dd/yyyy",provider,DateTimeStyles.None,outdateTime10);dateString="notadate";//Exception:ThestringwasnotrecognizedasavalidDateTime.Thereisanunknownwordstartingatindex0.DateTimedateTime11;//1/1/000112:00:00AMboolisSuccess2=DateTime.TryParseExact(dateString,"MM/dd/yyyy",provider,DateTimeStyles.None,outdateTime11);dateString="TueDec30,2015";DateTimedateTime12;//1/1/000112:00:00AM//Exception:StringwasnotrecognizedasavalidDateTimebecausethedayofweekwasincorrect.boolisSuccess3=DateTime.TryParseExact(dateString,"MM/dd/yyyy",provider,DateTimeStyles.None,outdateTime12);dateString="10-22-2015";DateTimedateTime13;//1/1/000112:00:00AMboolisSuccess4=DateTime.TryParseExact(dateString,"MM/dd/yyyy",provider,DateTimeStyles.None,outdateTime13);dateString="10-22-2015";DateTimedateTime15;//10/22/201512:00:00AMboolisSuccess5=DateTime.TryParseExact(dateString,"MM-dd-yyyy",provider,DateTimeStyles.None,outdateTime15);dateString="10-12-2015";//Output:10/22/201512:00:00AMDateTimedateTime14;boolisSuccess6=DateTime.TryParseExact(dateString,newstring[]{"MM/dd/yyyy","MM-dd-yyyy","MM.dd.yyyy"},provider,DateTimeStyles.None,outdateTime14);

The DateTime struct has several methods for parsing a string into a DateTime. We will discuss individual differences:

Difference between Parse() and ConvertToDateTime()

Both these two methods are almost similar except for the following differences:

If the string value is null, Parse() throws an Exception while ConvertToDateTime() returns DateTime.MinValue.

In Parse, you can pass one extra parameter called DataTimeSyles, which is not available ConvertToDateTime().

Lastly, Convert.ToDateTime uses DateTime.Parse internally, with the current culture.

Difference betweenParse() and ParseExact()

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").

Difference betweenParse() and TryParse()

The DateTime.TryParse(), the method is similar to the DateTime.Parse(String) method, except that the DateTime.TryParse() method does not throw an exception if the conversion fails. DateTime.TryParse() always returns DateTime.MinValue if conversion fails, but Parse() throws an exception.

Difference betweenDateTime.TryParse() and DateTime.TryParseExact()

DateTime.TryParse() and DateTime.TryParseExact() are similar except format parameter. DateTime.TryParseExact() uses an extra parameter for a format not available in DateTime.TryParse(). Format parameter helps to convert some custom string format. But DateTime.TryParse() returns DateTimenMinValue if any custom date is provided.

Thus, use TryParse() when you want to attempt a parse and handle invalid data immediately (instead of throwing the exception) and ParseExact() when the format you are expecting is not a standard format or when you want to limit to one particular standard format for efficiency.

If you're sure the string is a valid DateTime, and you know the format, you could also consider the DateTime.ParseExact() or DateTime.TryParseExact() methods.

Conclusion

In this article, we discussed parsing DateTime in C# in different ways and their differences. I hope this helps. Choose the appropriate method as per your data.

String To DateTime Conversion In C# (2024)

FAQs

Can we convert string to DateTime in C#? ›

In C#, there are several different ways to change a string into a datetime. Nonetheless, a DateTime object can be created from a date and time string in C#. The techniques are: Parse(), ParseExact(), TryParse() and TryParseExact().

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 empty string to DateTime in C#? ›

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

How to get DateTime string 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.

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 date only to DateTime in C#? ›

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

How to add string time to datetime in C#? ›

Convert a String to a Date

Parse(dateString); for any important work because the string you have might be in an unexpected format that parses into a DateTime without error, but is not the date you expected. If you have a complex custom date format, you can specify it exactly using . NET custom string components.

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 extract date from string in C#? ›

Follow the below steps to implement the idea:
  1. Create a regex expression to extract all the present dates from the string.
  2. Use Pattern class to compile the regex formed.
  3. Use the matcher function to find.
  4. If it is valid, return true. Otherwise, return false.
Mar 23, 2023

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 format string in C#? ›

In C#, Format() is a string method. This method is used to replace one or more format items in the specified string with the string representation of a specified object.In other words, this method is used to insert the value of the variable or an object or expression into another string.

How to use convert ToDateTime in C#? ›

ToDateTime(String, IFormatProvider) Method. This method is used to convert the specified string representation of a number to an equivalent date and time, using the specified culture-specific formatting information.

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

string date = "16/09/2019"; DateTime result = DateTime. Parse(date); Console. WriteLine(result); In the above example, the output will be 09/16/2019 12:00:00 AM , which is the DateTime equivalent of the string “16/09/2019”.

How does DateTime work in C#? ›

DateTime is a struct in C# that represents an instant in time, typically expressed as a date and time of day. It is available in the System namespace and has various constructors, fields, properties, methods, and operators to work with dates and times.

How to call DateTime in C#? ›

Properties of DateTime in C#
  1. We can get the name of the day from the week with the help of the DayOfWeek property.
  2. To get the day of the year, we will use DayOfYear property.
  3. To get time in a DateTime, we use TimeOfDay property.
  4. Today property will return the object of the DateTime, which is having today's value.

How to convert string to DateOnly? ›

ParseExact(String, String, IFormatProvider, DateTimeStyles)

Converts the specified string representation of a date to its DateOnly equivalent using the specified format, culture-specific format information, and style.

How to convert string to Smalldatetime in C#? ›

ToDateTime("2010-20-12 13:30:00"); //Second Convert DateTime to formatted string string t_time; t_time = dt. ToString("yyyy-dd-MM hh:mm tt");

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

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 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 ();

Top Articles
Latest Posts
Article information

Author: Jerrold Considine

Last Updated:

Views: 5375

Rating: 4.8 / 5 (78 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Jerrold Considine

Birthday: 1993-11-03

Address: Suite 447 3463 Marybelle Circles, New Marlin, AL 20765

Phone: +5816749283868

Job: Sales Executive

Hobby: Air sports, Sand art, Electronics, LARPing, Baseball, Book restoration, Puzzles

Introduction: My name is Jerrold Considine, I am a combative, cheerful, encouraging, happy, enthusiastic, funny, kind person who loves writing and wants to share my knowledge and understanding with you.