This post will discuss how to validate a date string in C#.

The DateTime.TryParseExact() method is the recommended approach to convert the string representation of a date and time to its DateTime equivalent. It returns a boolean value indicating whether the specified string is converted successfully or not.

The following sample illustrates the simple use of the TryParseExact() method.

Download  Run Code

Output:

Converted ’06/24/2018 10:00:00 AM -05:00′ to 24-06-2018 08:30:00 PM (Local).

 
To parse a string representing UTC, you can use the round-trip (O, o) format specifier.

Download  Run Code

Output:

Converted ‘2018-06-24T10:00:00.0805924Z’ to 24-06-2018 10:00:00 AM (Utc).

That’s all about validating a date string in C#.