TheDeveloperBlog.com

Home | Contact Us

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

C# DateTime.TryParse Example

This C# example program demonstrates the DateTime.TryParse method.

DateTime.TryParse. A string may contain a valid time representation.

But there is a possibility it is invalid. We convert it into a DateTime instance using the DateTime.TryParse method. This makes errors easy to recover from.

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. It returns true if the parse succeeded, and false otherwise.

Tip: You can use it in the if conditional, and it fills the out DateTime parameter.

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

The .NET Framework provides many versions of TryParse methods you can use. You do not need to test the resulting Boolean value from TryParse in an if-statement, but often this pattern is used to see if the parsing succeeded.

If-Statement: Else If, Else

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

Validity. If you are assured of the validity of your string input, you can use the DateTime.Parse method instead. This has somewhat simpler syntax and is likely faster on valid input.

Parse

Also: There are versions called ParseExact and TryParseExact. They provide a way to assert more control over the parsing algorithm.

TryParseExact. Next we see the DateTime.TryParseExact method. This method is actually more useful than ParseExact in many programs. It enhances performance and makes your program simpler when you have to deal with lots of invalid date strings.

In the .NET Framework, the InvariantCulture value is found in System.Globalization, so that namespace must be specified. You can see in this program that the TryParseExact method succeeds.

C# program that uses TryParseExact

using System;
using System.Globalization;

class Program
{
    static void Main()
    {
	string dateString = "Mon 16 Jun 8:30 AM 2008"; // <-- Valid
	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

Example 3. 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.

Program 2 that uses TryParseExact: C#

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

The DateTime.TryParseExact method receives a formatting string and converts an input string into a DateTime instance. The formatting string must adhere to the standard .NET Framework style. This requirement steepens the learning curve.

Summary. We used the DateTime.TryParse public static method in the C# language and proved that it works on different types of strings without throwing exceptions. The TryParse method uses the tester-doer pattern.

And: It is ideal when you are not positive your input will be valid and want to add error handling or recovery for invalid dates.


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