
You have a string that may contain a valid representation of the date and time, but there is a possibility it is invalid. Convert it into a DateTime instance using the DateTime.TryParse method, which is ideal for this purpose.
Here we test the DateTime.TryParse method. This is very useful and does the same thing as DateTime.Parse, but does not throw any exceptions. It returns true if the parse succeeded, and false otherwise. You can use it in the if conditional, and it fills the out DateTime parameter.
This C# example program demonstrates the DateTime.TryParse method.
Program that uses DateTime.TryParse [C#]
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
InvalidTesting result of DateTime.TryParse. The .NET Framework provides many versions of TryParse methods you can use on various value types. 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. The DateTime.TryParse method invocations above first return true and then false, indicating the first string contained a valid date representation and the second string did not.
TryParse Overview
Here we mention other useful methods in the .NET Framework for parsing dates and times. If you are assured of the validity of your string input, you can use the DateTime.Parse method instead, which has somewhat simpler syntax and is likely faster on valid input. This site also has many resources on the DateTime formatting options. Additionally, there are versions of the parsing methods called ParseExact and TryParseExact, which provide a way for you to assert more control over the parsing algorithm.
DateTime.Parse String MethodHere we looked at an example of using the DateTime.TryParse public static method in the C# programming language and proved that it works on different types of strings without throwing exceptions. The TryParse method uses the tester-doer pattern and is ideal when you are not positive your input will be valid and want to add error handling or recovery for invalid dates.
Time Representations