C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
IfResult: TryParse returns true and then false, indicating the first string contained a valid date representation and the second did not.
True, FalseC# 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
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
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
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.