TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# DateTime.TryParse and TryParseExact

Use the DateTime.TryParse method and TryParseExact to parse dates and times.
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.DateTime.ParseDateTime
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.

If: 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.

If

Result: TryParse returns true and then false, indicating the first string contained a valid date representation and the second did not.

True, False
C# program that uses DateTime.TryParse using System; class Program { static void Main() { // 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 } } } Output 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.

C# program that uses TryParseExact using System; using System.Globalization; class Program { static void Main() { 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); } } } Output 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.

String: The formatting string must adhere to the standard .NET Framework style. This requirement steepens the learning curve.

C# program that uses TryParseExact 2 using System; using System.Globalization; class Program { static void Main() { 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"); } } } Output 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.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf