
In some program contexts, you may have a specific format pattern string that you want to parse dates with. The DateTime.TryParseExact method provides a way to specify a format string and use it to convert a string into a DateTime instance. This uses uses the tester-doer pattern.
TryParse OverviewHere we see the DateTime.TryParseExact method in the C# language, which 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.
This C# example program demonstrates the DateTime.TryParseExact method.
Program that uses TryParseExact [C#]
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 AMNote on namespaces used. The InvariantCulture value is found in System.Globalization, so that namespace must be specified. You can see that the TryParseExact method succeeds here.
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 for this method. When possible, it is probably advisable to use TryParse.
DateTime.ParseExact Usage Time Representations