PowerShell: Parsing Date and Time

Parsing Date and Time

Parsing a date and/or time information is tricky because formatting depends on the regional settings. This is why PowerShell can convert date and time based on your regional settings or in a culture-neutral format. Let’s assume this date:

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.

18 thoughts on “PowerShell: Parsing Date and Time

  1. Heya i’m for the first time here. I found this board and I find It really useful & it helped me out much. I hope to give something back and aid others like you aided me.

  2. I simply want to say I am just very new to weblog and absolutely savored this web site. Most likely I’m planning to bookmark your website . You amazingly have terrific articles and reviews. Bless you for sharing your webpage.

  3. I needed to thank you for this great read!! I definitely enjoying each little bit of it I’ve you bookmarked to take a look at new stuff you post

  4. Spot on with this write-up, I honestly think this site needs far more attention. I’ll probably be returning to read through more, thanks for the information!

  5. Hi there, maybe you are not here any more. maybe you are..
    I have problems parsing this string to date time and wondering if there is a way to do it?
    $fileName= “AllDBs-2015-03-07_0500.zip”
    $dateFormat = ‘AllDB\s-yyyy-MM-dd_hhmm.\zip’

    THX!

    1. Hi Phil

      Sorry for the late reply. Please try the following:


      PS> $fileName="AllDBs-2015-03-07_0500.zip"
      PS> $pattern="AllDB\s-yyyy-MM-dd_HHmm.\zip"
      PS> [DateTime]::ParseExact($fileName,$pattern,$null)

      07 March 2015 05:00:00

  6. Bizarre!
    [datetime]’05/07/2018′
    maandag 7 mei 2018 00:00:00 (monday 7th may)

    ’05/07/2018′ -as [datetime]
    donderdag 5 juli 2018 00:00:00 (thursday 5th july)

    1. [DateTime] may honour culture in some senses, but it assumes that short format date strings (such as those found in many log files for example) are in US format (i.e. mm/dd/yy).

      On the other hand, using “-as [DateTime]” will respect the local culture.

      On my system:

      PS:> Get-Culture | Format-List Name, DisplayName, EnglishName

      Name : en-GB
      DisplayName : English (United Kingdom)
      EnglishName : English (United Kingdom)

      PS:> Get-Culture | Select -Expand DateTimeFormat | Select ShortDatePattern

      ShortDatePattern —————-
      dd/MM/yyyy

      In my opinion, [DateTime] should, like Get-Date, respect culture.

      This could be fixed by introducing to new two accelerators:

      [IsoDateTime]

      and

      [LocalDateTime]

      …and subsequently deprecating [DateTime].

Leave a Reply to Gregory Despain Cancel reply

Your email address will not be published.