Monthly Archive

Categories

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

Comments are closed.