Beta 42

Research and Development

Menu

PowerShell - Parsing Date and Time

PS> $date = '1/6/2013'

If you convert this to a datetime type, PowerShell always uses the culture-neutral format (US format), regardless of your regional settings. The output is shown here on a German system:

PS> [DateTime]$date
Sonntag, 6. Januar 2013 00:00:00

To use your regional datetime format, use the Parse() method which is part of the DateTime type, like this:

PS> [DateTime]::Parse($date)
Samstag, 1. Juni 2013 00:00:00

Alternately, you can use Get-Date and the -date parameter:

PS> Get-Date -Date $date
Samstag, 1. Juni 2013 00:00:00

Parsing Custom DateTime Formats

Sometimes, date and time information may not conform to standards, and still you'd like to interpret that information correctly as date and time.

That's when you can use ParseExact() provided by the DateTime type. Here's an example:

PS> $timeinfo = '12 07 2012 18 02'

To tell PowerShell what piece of information belongs to which datetime part, you submit a template like this:

PS> $template = 'HH mm yyyy dd MM'

This template defines the custom format to specify hours first (HH), then minutes (mm), then the year (yyyy), the day (dd) and the month (MM).

Now let's use the template to interpret the raw datetime information:

PS> $timeinfo = '12 07 2012 18 02'
PS> $template = 'HH mm yyyy dd MM'
PS> [DateTime]::ParseExact($timeinfo, $template, $null) 
Samstag, 18. Februar 2012 12:07:00

Voilá! To define patterns, here are the placeholders you can use (note that they are case-sensitive!):

d     Day of month 1-31
dd    Day of month 01-31
ddd   Day of month as abbreviated weekday name
dddd  Weekday name
h     Hour from 1-12
H     Hour from 1-24
hh    Hour from 01-12
HH    Hour from 01-24
m     Minute from 0-59
mm    Minute from 00-59
M     Month from 1-12
MM    Month from 01-12
MMM   Abbreviated Month Name
MMMM  Month name
s     Seconds from 1-60
ss    Seconds from 01-60
t     A or P (for AM or PM)
tt    AM or PM
yy    Year as 2-digit
yyyy  Year as 4-digit
z     Timezone as one digit
zz    Timezone as 2-digit
zzz   Timezone

Parsing Extra Text

Using ParseExact() to parse custom datetime formats only works 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.