DateTime.TryParse and TryParseExact
This page was last reviewed on Nov 2, 2023.
Dot Net Perls
DateTime.TryParse. A string may contain a valid time representation. But there is a possibility it is invalid. There is a way to convert safely the string to a DateTime.
We convert the string into a DateTime instance using the DateTime.TryParse method. This makes errors easy to recover from. A boolean (ok) is returned.
An example. Here we test the DateTime.TryParse method. This is useful—it does the same thing as DateTime.Parse, but does not throw any exceptions.
Return TryParse returns true if the parse succeeded, and false otherwise. The bool indicates whether the parse was "ok."
Tip You can use TryParse in the if conditional, and it fills the out DateTime parameter.
Detail You do not need to test the result from TryParse in an if-statement, but often this pattern is used to see if the parsing succeeded.
Result TryParse returns true and then false, indicating the first string contained a valid date representation and the second did not.
true, false
using System; // Use DateTime.TryParse when input is valid. string input = "2000-02-02"; DateTime dateTime; if (DateTime.TryParse(input, out dateTime)) { Console.WriteLine(dateTime); } // Use DateTime.TryParse when input is bad. string badInput = "???"; DateTime dateTime2; if (DateTime.TryParse(badInput, out dateTime2)) { Console.WriteLine(dateTime2); } else { Console.WriteLine("Invalid"); // <-- Control flow goes here }
2/2/2000 12:00:00 AM Invalid
TryParseExact. Next we see the DateTime.TryParseExact method. TryParseExact enhances performance and makes your program simpler when you have to deal with lots of invalid date strings.
Tip In the .NET Framework, the InvariantCulture value is found in System.Globalization, so that namespace must be specified.
Note You can see in this program that the TryParseExact method succeeds. True is returned by TryParseExact.
using System; using System.Globalization; string dateString = "Mon 16 Jun 8:30 AM 2008"; string format = "ddd dd MMM h:mm tt yyyy"; DateTime dateTime; if (DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime)) { Console.WriteLine(dateTime); }
6/16/2008 8:30:00 AM
Invalid formats. When you need DateTime.TryParseExact, you are usually dealing with invalid formats of dates, or nonexistent dates.
Here We see an obviously incorrect date, and DateTime.TryParseExact will return false.
Info The DateTime.TryParseExact method receives a formatting string and converts an input string into a DateTime instance.
Detail The formatting string must adhere to the standard .NET Framework style. This requirement steepens the learning curve.
using System; using System.Globalization; string dateString = "???"; string format = "ddd dd MMM h:mm tt yyyy"; DateTime dateTime; if (DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime)) { Console.WriteLine(dateTime); } else { Console.WriteLine("Not a date"); }
Not a date
Validity. If you are assured of the validity of your string input (from previous testing in the code), you can use the DateTime.Parse method instead.
Note Parse has somewhat simpler syntax and is likely faster on valid input. On invalid input, Parse() will not work as well.
Also There are versions called ParseExact and TryParseExact. They provide a way to assert more control over the parsing algorithm.
A summary. We used the DateTime.TryParse public static method in the C# language. And we proved that it works on different types of strings without throwing exceptions.
The TryParse method uses the tester-doer pattern. It is ideal when you are not positive your input will be valid and want to add error handling or recovery for invalid dates.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 2, 2023 (edit).
© 2007-2024 Sam Allen.