String To DateTime Conversion In C#

Introduction
 
DateTime is a struct type which is mostly used in application to manage date, date-time, time, etc. Most of time we get date in form of string and we need parsing to DateTime object to perform some operation like date difference, weekday, month name, etc. For instance, there is a string value (“12/10/2015”) and our requirement is to find out weekday (Sunday or Monday..) of date. In this scenario we need to convert string value to DateTime object and then use WeekDay property(obj.WeekDay) to find out week day. We can accomplish the same by built-in methods like Convert.ToDateTime(), DateTime.Parse(),DateTime.ParseExact(), DateTime.TryParse(), and DateTime.TryParseExact().
 
Now a question arises, why we have so many methods to parse a string to DateTime object. Is it really necessary? If yes, then in which scenario we need to use them. We will discuss how all these DateTime conversion methods are used and what are the differences 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 couple of overload methods but two are mostly important:
 
ToDateTime(string value)
 
Here value is string representation of date and time. For instance, Convert.DateTime(“1/1/2010”)
 
ToDateTime(string value, IFormatProvider provider)
 
Value: It is string representation of date and time.
Provider: It is an object which provides culture specific info. 
  1. CultureInfo culture = new CultureInfo("en-US");    
  2. DateTime tempDate = Convert.ToDateTime("1/1/2010 12:10:15 PM", culture);    
Here “en-US” is culture information about United State of America. You can change as per culture like French, German, etc.
 
If string value is not null then it internally calls DateTime.Parse() to give the result. On the other hand if 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 FormatException issue. Let’s have a look at the following examples: 
  1. // Convert.ToDateTime()  
  2. string dateString = null;  
  3.   
  4. // Convert a null string.  
  5. DateTime dateTime10 = Convert.ToDateTime(dateString); // 1/1/0001 12:00:00 AM  
  6. dateString = "not a date";  
  7. // Exception: The string was not recognized as a valid DateTime. 
  8. // There is an unknown word starting at index 0.  
  9. DateTime dateTime11 = Convert.ToDateTime(dateString);  
  10.              
  11. dateString = "Tue Dec 30, 2015";  
  12. // Exception: String was not recognized as a valid DateTime because the day of week was incorrect.  
  13. 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 string representation of date and time. For instance, DateTime.Parse(“01/10/2015”);
 
DateTime.Parse(String value, IFormatProvider provider)
 
Value: It is 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 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 which helps to ignore all spaces present in string while it parse.
 
More on this visit here.
 
If value is null then it returns ArgumentNullException and same way if value contains some invalid date format then it returns FormatException.
Here are couple of examples: 
  1. string dateString = null;  
  2. // Exception: Argument null exception
  3. DateTime dateTime10 = DateTime.Parse(dateString); 
  4.   
  5. dateString = "not a date";  
  6. // Exception: The string was not recognized as a valid DateTime. 
  7. // There is an unknown word starting at index 0.  
  8. DateTime dateTime11 = DateTime.Parse(dateString);  
  9.   
  10. dateString = "Tue Dec 30, 2015";  
  11. // Exception: String was not recognized as a valid DateTime because the day of week was incorrect.  
  12. DateTime dateTime12 = DateTime.Parse(dateString);  

DateTime.ParseExact()
 
It converts specified string to equivalent DateTime with specified format and culture. The string value of format must match with 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 string representation of date and time.
Format: It is format specifier that defines a date look like after conversion.
Provider: It is an object which specify about culture info.
 
DateTime.ParseExact(string value, string format, IFormatProvider provider, DateTimeStyles style)
 
Value: It is string representation of date and time.
Format: It is format specifier that defines a date look like after conversion.
Provider: It is an object which specify about 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 string representation of date and time.
Formats: It is format specifier that defines a date look like after conversion. It is a string array which contains a list of formats and at least one format must match with string(value) to convert DateTime object.
Provider: It is an object which specify culture info.
Style: It defines the formatting options that customize string parsing for some date and time parsing methods.
 
If the value is null then it returns ArgumentNullException and same way if value contains some invalid date format then it returns FormatException. The format must match with string date time or it throws FormatException. So to overcome this issue you can use string format array which has some possibilities. Suppose your date may be in format like “12/12/2015” or “12-12-2015”, here you need to pass string array with format like “MM/dd/yyyy” and “MM-dd-yyyy”.
 
Here are couples of examples that may help you understand it better: 
  1. // Convert a null string.  
  2. string dateString = null;  
  3. CultureInfo provider = CultureInfo.InvariantCulture;  
  4. // It throws Argument null exception  
  5. DateTime dateTime10 = DateTime.ParseExact(dateString, "mm/dd/yyyy", provider);  
  6.   
  7. dateString = "not a date";  
  8. // Exception: The string was not recognized as a valid DateTime. There is an unknown word starting at index 0.              
  9. DateTime dateTime11 = DateTime.ParseExact(dateString, "mm/dd/yyyy", provider);  
  10.   
  11. dateString = "Tue Dec 30, 2015";  
  12. // Exception: String was not recognized as a valid DateTime because the day of week was incorrect.  
  13. DateTime dateTime12 = DateTime.ParseExact(dateString, "mm/dd/yyyy", provider);  
  14.   
  15. dateString = "10-22-2015";  
  16. // Exception: String was not recognized as a valid DateTime because the day of week was incorrect.  
  17. DateTime dateTime13 = DateTime.ParseExact(dateString, "MM-dd-yyyy", provider); // 10/22/2015 12:00:00 AM  
  18. string temp = dateTime13.ToString();  
  19.   
  20. dateString = "10-12-2015";  
  21. // Output: 10/22/2015 12:00:00 AM  
  22. DateTime dateTime16 = DateTime.ParseExact(dateString, new string[] { "MM.dd.yyyy""MM-dd-yyyy""MM/dd/yyyy" }, provider, DateTimeStyles.None); 
  23.  
DateTime.TryParse()
 
It converts specified string data to equivalent datetime and returns Boolean value after parsing which indicates parsing is 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 which helps to ignore all spaces present in string while it parse.
Result: It holds the DateTime value after parsing.
 
TryParse() always try to parse the string value datetime. If conversion succeeded then it returns correct DateTime value and MinValue(1/1/0001 12:00:00 AM) if conversion failed. If string value is null or empty and you are trying to convert it DateTime then it returns MinValue only. Secondly, it always returns a Boolean value which indicates conversion succeeded or failed. If conversion succeeded then True otherwise it returns False.
 
It is most likely as DateTime.Parse(). But only difference is that it doesn’t throw any exception when conversion failed rather it returns MinValue of DateTime.
 
Here are couple of examples: 
  1. string dateString = null;  
  2. // Convert a null string.  
  3. DateTime dateTime10;  
  4. bool isSuccess = DateTime.TryParse(dateString, out dateTime10); // 1/1/0001 12:00:00 AM  
  5.   
  6. dateString = "not a date";  
  7. DateTime dateTime11;  
  8. bool isSuccess1 = DateTime.TryParse(dateString, out dateTime11); // 1/1/0001 12:00:00 AM  
  9.   
  10. dateString = "Tue Dec 30, 2015";  
  11. DateTime dateTime12;  
  12. bool isSuccess2 = DateTime.TryParse(dateString, out dateTime12); // 1/1/0001 12:00:00 AM  

DateTime.TryParseExact()
 
It converts specified string to equivalent DateTime with specified format and culture. The string value of format must match with string value of datetime. It is available in System (mscorlib.dll) namespace and introduced .NET framework 2.0 onwards. It contains tje 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 format specifier that defines a date look like after conversion.
Provider: It is an object which specify about 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 format specifier that defines a date look like after conversion. It is a string array which contains a list of formats and at least one format must match with string (value) to convert DateTime object.
Provider: It is an object which specify about culture 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:
  • string value is null.
  • string value is blank.
  • string is not correct date.
  • string is not match with format provided. 
It throws exception only if DateTimeStyle value is not valid otherwise returns MinValue.
Secondly, it always returns a Boolean value (true or false) to indicate whether conversion succeeded. It returns True if conversion succeeded and False if conversion failed.
 
The following are some examples that will help you to understand it better:
  1. string dateString = null;  
  2. CultureInfo provider = CultureInfo.InvariantCulture;  
  3. DateTime dateTime10; // 1/1/0001 12:00:00 AM  
  4. bool isSuccess1 = DateTime.TryParseExact(dateString, "MM/dd/yyyy", provider, DateTimeStyles.None, out dateTime10);  

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

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

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

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

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

Analysis
 
The DateTime struct has couple of methods for parsing a string into a DateTime. We will discuss about individual differences:
 
Difference between Parse() and ConvertToDateTime()
 
Both these two methods are almost similar except the following differences:
 
If string value is null then Parse() throws 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 extra parameter which is not available in Parse(). Format parameter helps to convert a string date value to DateTime object when a date is different format like “11-23-2015”(Format should be “MM-dd-yyyy”).
 
Difference between Parse() and TryParse()
 
The DateTime.TryParse(), 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 exception.
 
Difference between DateTime.TryParse() and DateTime.TryParseExact()
 
DateTime.TryParse() and DateTime.TryParseExact() are similar except format parameter. DateTime.TryParseExact() uses a extra parameter for format which is 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 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 the article we discussed about parsing DateTime in C# in different ways and what are the differences between them. Choose appropriate method as per data. Hope this helps.

Up Next
    Ebook Download
    View all
    Learn
    View all