The DateTime TryParse method converts the string representation of a date and time to a DateTime object and returns true
if the conversion was successful and false
if otherwise.
TryParse has four overloads:
This shot will cover the most commonly used one, TryParse(String, DateTime).
This method converts the string representation of a date and time to the equivalent DateTime object. The method returns True
if the conversion was successful and false
if otherwise.
public static bool TryParse (string? s, out DateTime? result);
s
: A string containing a date and time to convert.result
: When this method returns, result
contains the DateTime
value equivalent to the date and time contained in s
if the conversion succeeded and MinValue
if the conversion failed.Returns true
if the string s
was converted successfully; otherwise, false
.
The
DateTime.TryParse(String, DateTime)
method is similar to theDateTime.Parse(String)
method, except that theTryParse(String, DateTime)
method does not throw an exception if the conversion fails.
The following example passes several date and time strings to the DateTime.TryParse(String, DateTime)
method:
using System;using System.Globalization;public class Example{public static void Main(){DateTime dateValue; // to store the results// Example 1string dateString1 = "05/01/2020 14:57:32.8";if (DateTime.TryParse(dateString1, out dateValue))Console.WriteLine("Converted '{0}' to {1}.", dateString1, dateValue);elseConsole.WriteLine("Unable to parse '{0}'.", dateString1);// Example 2string dateString2 = "1 May 2020 2:57:32.8 PM";if (DateTime.TryParse(dateString2, out dateValue))Console.WriteLine("Converted '{0}' to {1}.", dateString2, dateValue);elseConsole.WriteLine("Unable to parse '{0}'.", dateString2);// Example 3string dateString3 = "not a date";if (DateTime.TryParse(dateString3, out dateValue))Console.WriteLine("Converted '{0}' to {1}.", dateString3, dateValue);elseConsole.WriteLine("Unable to parse '{0}'.", dateString3);}}// The examples above display the following:// Converted '05/01/2020 14:57:32.8' to 5/1/2020 2:57:32 PM.// Converted '1 May 2020 2:57:32.8 PM' to 5/1/2020 2:57:32 PM .// Unable to parse 'not a date'.
Free Resources