String To DateTime Conversion In C#

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. 
CultureInfo culture = new CultureInfo("en-US");    
DateTime tempDate = Convert.ToDateTime("1/1/2010 12:10:15 PM", 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()  
string dateString = null;  
  
// Convert a null string.  
DateTime dateTime10 = Convert.ToDateTime(dateString); // 1/1/0001 12:00:00 AM  
dateString = "not a date";  
// Exception: The string was not recognized as a valid DateTime. 
// There is an unknown word starting at index 0.  
DateTime dateTime11 = Convert.ToDateTime(dateString);  
             
dateString = "Tue Dec 30, 2015";  
// Exception: String was not recognized as a valid DateTime because the day of week was incorrect.  
DateTime dateTime12 = 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 is here.

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.

string dateString = null;  
// Exception: Argument null exception
DateTime dateTime10 = DateTime.Parse(dateString); 
  
dateString = "not a date";  
// Exception: The string was not recognized as a valid DateTime. 
// There is an unknown word starting at index 0.  
DateTime dateTime11 = DateTime.Parse(dateString);  
  
dateString = "Tue Dec 30, 2015";  
// Exception: String was not recognized as a valid DateTime because the day of week was incorrect.  
DateTime dateTime12 = 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 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.

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.

// Convert a null string.  
string dateString = null;  
CultureInfo provider = CultureInfo.InvariantCulture;  
// It throws Argument null exception  
DateTime dateTime10 = DateTime.ParseExact(dateString, "mm/dd/yyyy", provider);  
  
dateString = "not a date";  
// Exception: The string was not recognized as a valid DateTime. There is an unknown word starting at index 0.              
DateTime dateTime11 = DateTime.ParseExact(dateString, "mm/dd/yyyy", provider);  
  
dateString = "Tue Dec 30, 2015";  
// Exception: String was not recognized as a valid DateTime because the day of week was incorrect.  
DateTime dateTime12 = DateTime.ParseExact(dateString, "mm/dd/yyyy", provider);  
  
dateString = "10-22-2015";  
// Exception: String was not recognized as a valid DateTime because the day of week was incorrect.  
DateTime dateTime13 = DateTime.ParseExact(dateString, "MM-dd-yyyy", provider); // 10/22/2015 12:00:00 AM  
string temp = dateTime13.ToString();  
  
dateString = "10-12-2015";  
// Output: 10/22/2015 12:00:00 AM  
DateTime dateTime16 = DateTime.ParseExact(dateString, new string[] { "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.

string dateString = null;  
// Convert a null string.  
DateTime dateTime10;  
bool isSuccess = DateTime.TryParse(dateString, out dateTime10); // 1/1/0001 12:00:00 AM  
  
dateString = "not a date";  
DateTime dateTime11;  
bool isSuccess1 = DateTime.TryParse(dateString, out dateTime11); // 1/1/0001 12:00:00 AM  
  
dateString = "Tue Dec 30, 2015";  
DateTime dateTime12;  
bool isSuccess2 = DateTime.TryParse(dateString, out dateTime12); // 1/1/0001 12:00:00 AM  

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 string value is blank.
  • The string is not the correct date.
  • The string is 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.

string dateString = null;  
CultureInfo provider = CultureInfo.InvariantCulture;  
DateTime dateTime10; // 1/1/0001 12:00:00 AM  
bool isSuccess1 = DateTime.TryParseExact(dateString, "MM/dd/yyyy", provider, DateTimeStyles.None, out dateTime10);  

dateString = "not a date";  
// Exception: The string was not recognized as a valid DateTime. There is an unknown word starting at index 0.  
DateTime dateTime11; // 1/1/0001 12:00:00 AM  
bool isSuccess2 = DateTime.TryParseExact(dateString, "MM/dd/yyyy", provider, DateTimeStyles.None, out dateTime11);  

dateString = "Tue Dec 30, 2015";
DateTime dateTime12; //1/1/0001 12:00:00 AM    
// Exception: String was not recognized as a valid DateTime because the day of week was incorrect.  
bool isSuccess3 = DateTime.TryParseExact(dateString, "MM/dd/yyyy", provider, DateTimeStyles.None, out dateTime12);  
dateString = "10-22-2015";  

DateTime dateTime13; // 1/1/0001 12:00:00 AM  
bool isSuccess4 = DateTime.TryParseExact(dateString, "MM/dd/yyyy", provider, DateTimeStyles.None, out dateTime13);  
dateString = "10-22-2015";  

DateTime dateTime15; // 10/22/2015 12:00:00 AM  
bool isSuccess5 = DateTime.TryParseExact(dateString, "MM-dd-yyyy", provider, DateTimeStyles.None, out dateTime15);  

dateString = "10-12-2015";  
// Output: 10/22/2015 12:00:00 AM  
DateTime dateTime14;   
bool isSuccess6 = DateTime.TryParseExact(dateString, new string[]{ "MM/dd/yyyy", "MM-dd-yyyy", "MM.dd.yyyy"}, provider, DateTimeStyles.None, out dateTime14);   

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 between Parse() 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 between Parse() 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 between DateTime.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.


Similar Articles