header image

Date conversions

Posted by: | December 23, 2014 Comments Off on Date conversions |

Saw a question regarding the conversion of dates in UK format DD/MM/YYYY to US format MM/DD/YYYY

 

Using 25 December 2014 as an example

If you have a dat in US format you can do this

£> $sd = ’12/25/2014′
£> $d = [datetime]$sd
£> $d

25 December 2014 00:00:00

 

$d = [datetime]$sd   creates a datetime object

 

If you try that in UK format

£> $sduk = ’25/12/2014′
£> $d = [datetime]$sduk
Cannot convert value "25/12/2014" to type "System.DateTime". Error: "String was not recognized as a valid DateTime."
At line:1 char:1
+ $d = [datetime]$sduk
+ ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvalidCastParseTargetInvocationWithFormatProvider

 

It fails.

.NET expects strings representing dates to be in US format.

£> [datetime]’25 December 2014′

25 December 2014 00:00:00

works but the data isn’t in that format.

 

The easiest way I know to create a date object when you have UK format strings would be:

£> $sd = ’25/12/2014′ -split ‘/’
£> $sd
25
12
2014
£> $d = Get-Date -Day $sd[0] -Month $sd[1] -Year $sd[2]
£> $d

25 December 2014 18:36:05

under: PowerShell Basics

Comments are closed.

Categories