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

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

4 Responses to Date conversions

  1. Ayo says:

    Hi,

    Whats wrong in using the Get-Date -uformat , you can manipulate it this way, and just convert it back to a [datetime] object by manually casting it. e.g
    $oldtime = Get-Date -Uformat ‘%d/%m/%y’
    $newtime = [datetime]$oldtime

  2. If you’re using UK format dates and your locale is set to UK, then you can use get-date to convert the (uk format) string without having to split it up first:

    PS:\> get-date ’25/12/2014′

    25 December 2014 00:00:00

    I have some issues with the [DateTime] type accelerator and locale-specific dates and have created a bug entry on Connect here: https://connect.microsoft.com/PowerShell/feedback/details/1062130 Please vote if you agree, thanks!

  3. Andy Britton says:

    [datetime]::ParseExact(’25/12/2014′, “dd/MM/yyyy”, [System.Globalization.CultureInfo]::InvariantCulture)

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