Converting strings to dates

You’ll see many examples of this:

PS>  [datetime]’12/25/2016′

25 December 2016 00:00:00

This works great if the date is in US format – MM/DD/YYYY

For those of us who use different date formats – such as England DD/MM/YYYY – this approach won’t work

PS>  [datetime]’25/12/2016′
Cannot convert value “25/12/2016” to type “System.DateTime”. Error: “String was not recognized as a
valid DateTime.”
At line:1 char:1
+ [datetime]’25/12/2016′
+ ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvalidCastParseTargetInvocationWithFormatProvider

You need to rearrange the string  –  for example

$ds = ’25/12/2016′ -split ‘/’

PS>  [datetime](“{0}/{1}/{2}” -f $ds[1], $ds[0], $ds[2])

25 December 2016 00:00:00

PS>  Get-Date -Day $ds[0] -Month $ds[1] -Year $ds[2]

25 December 2016 10:44:45

or even simpler

PS>  Get-Date -Date ’25/12/2016′

25 December 2016 00:00:00

Not sure when the last option came in. Its in PowerShell v5

Advertisements
This entry was posted in Powershell Basics. Bookmark the permalink.

6 Responses to Converting strings to dates

  1. aanotheruser says:

    Hello Richard

    You can also use this approach for US or UK

    [datetime]”25/Dec/2011″
    [datetime]”Dec/25/2011″

    Both should work in either local

  2. Marc Rice says:

    You can also use the DateTime Methods Parse and ParseExact for more control when creating valid datetime objects from a string.

    [DateTime]::Parse(’25/12/2016′) will always use your system’s culture settings to convert the date (where [DateTime]’25/12/2016′ will attempt to use Culture Neutrual (US Format)). Nice for non-US or international users. Your Get-Date -Date ’25/12/2016′ example works the same way as [DateTime]::Parse() in that it uses the culture settings for conversion.

    [DateTime::ParseExact(’25/12/2016′,’dd/MM/yyyy’,$null) is great because it allows you to use a custom template (‘dd/MM/yyyy’) to parse the string into a datetime object. This is similar to your format string approach but without the extra needed step to split the string (which may be hard if the datetime info in the string is complex). This method is particularly useful for datetime info retrieved from filenames or log files that may have more non stardard formats in them for complactness or to exclude illegal characters.

    For example, [DateTime]::ParseExact(‘25122016′,’ddMMyyyy’,$null) and [DateTime]::ParseExact(‘122448P25Dec2016′,’HHmmsstddMMMyyyy’,$null) convert equally well into valid datetime objects.

    You should be able to use most of the format specifiers listed on this page to create the custom template to parse the string: https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx

  3. Brent Denny says:

    [datetime]$DateFromString = “25/12/2017 11:11:01 AM” -replace “^(\d{1,2})\/(\d{1,2})”,’$2/$1′
    Because we know that the type accelerator only accepts US time strings when all are numbers, here is a one-liner using RegEx replace to achieve the same thing.

    • Brent Denny says:

      to cater for different strings you could change the Regex to be
      “25-12-2017 11:11:01 AM” -replace “^(\d{1,2})(\/|\-|\s)(\d{1,2})(\/|\-|\s)”,’$3$2$1$2′
      This now allows for / or – or a space between the date portion of the string, it also forces the result to have the same separator in case the original had a mixture of separators in the string.

  4. Brent Denny says:

    “25-12-2017 11:11:01 AM” -replace “^(\d{1,2})([-/ ])(\d{1,2})([-/ ])”,’$3$2$1$2′
    This reduces the size of the RegEx even further, be careful the order of characters in the [ ] matters in this case as if you put the – in the middle of the / and ‘ ‘ it tries to act as a range and not a literal –
    Hope this helps!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s