O'Reilly logo

Microsoft® Visual Basic® .NET Programmer's Cookbook by Matthew MacDonald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required