Validate a User-Supplied Date

Problem

You want to convert a user-supplied string containing date information into a DateTime instance without introducing the possibility for error.

Solution

Use the DateTime.ParseExact method with a custom format string.

Discussion

The DateTime structure includes a Parse method that creates a DateTime instance from a string. However, this method is aggressive and prone to error. It tries everything possible to avoid throwing a FormatException, even ignoring unrecognized characters or filling in assumed dates. If this isn’t acceptable in your application, you can use the ParseExact method, which allows you to define the format you expect for the string. If the format does not match exactly, or there is any discrepancy ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.