devxlogo

Parsing strings with a custom pattern into a Date variable

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())

See also  Essential Measures for Safeguarding Your Digital Data
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist