C# DateTime is a struct type, which is mostly used in applications to manage date, date-time, time data types. Most of time, we get a date in 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 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
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.
CultureInfo culture = new CultureInfo("enUS"); 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:
// 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);
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 timeResult: 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 timeProvider: 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.
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
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.