datetime tryparse in csharp

Here's an example of using DateTime.TryParse() method in C# to parse a string into a DateTime object while handling any exceptions that may arise:

main.cs
string dateString = "2021-07-29 09:05:30";
DateTime resultDateTime;
if (DateTime.TryParse(dateString, out resultDateTime))
{
    Console.WriteLine("Successfully parsed date string: " + resultDateTime.ToString());
}
else
{
    Console.WriteLine("Failed to parse date string");
}
278 chars
11 lines

The TryParse() method returns a boolean value indicating whether or not the parsing operation was successful. If successful, the parsed DateTime object is output to the console as a string. If unsuccessful, an error message is output instead.

gistlibby LogSnag