Parsing Custom DateTime Formats (Part 2)

by May 7, 2012

In a previous tip we illustrated how you can use ParseExact() to parse custom datetime formats. This only works though if the date and time information does not contain extra characters except whitespace.

To parse date and time information that has extra text in the middle of it, you must escape any ambiguous character. Here's a sample:

PS> $raw = 'year 2012 and month 08'
PS> $pattern = '\year yyyy an\d \mon\t\h MM'
PS>
PS> [DateTime]::ParseExact($raw, $pattern, $null)

Note how in the pattern, each character that represents a date or time information is escaped. Other characters that are not placeholders for date or time information do not necessarily need to be escaped. If you are unsure, simply escape any character that is not meant to be a placeholder.

Twitter This Tip! ReTweet this Tip!