Parsing strings with a custom pattern into a Date variable

The Parse static method of the Date type does a good job in parsing an input string and returning a Date instance. It recognizes and accepts the commonly used separators for the date part, such as / or -, and : for the time. It also has overloaded versions that allow you to specify the culture of the input string, and whether the string can contain leading, trailing or inner white spaces to skip during the parsing. However, at times you may need more flexibility, and the need to parse date strings written in a specific and non-standard format. For example, this is necessary when you’re importing dates from a text file produced by some legacy application that used its own custom format. Say for example that instead of writing the US-standard 10/04/2003 it wrote 031004. Well, another method of the Date type comes to rescue, ParseExact, that allows you to specify the pattern of the input string, for both the date and time parts. Here’s a sample snippet that parses “031004 10:03 AM” into a Date variable:

Dim myDate As Date = Date.ParseExact( "031004 10:03 AM", "yyMMdd hh:mm tt", _    System.Globalization.DateTimeFormatInfo.InvariantInfo)MessageBox.Show(myDate.ToLongDateString() & " - " & myDate.ToLongTimeString())

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: