Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: VB7
Expertise: beginner
Dec 22, 2003



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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", _
MessageBox.Show(myDate.ToLongDateString() & " - " & myDate.ToLongTimeString())
Marco Bellinaso
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date