More on dates

My recent post on date conversions seems to have generated a fair bit of confusion and discussion. The original task was to read in a string from a CSV file that contained a date in UK format – DD/MM/YYYY and reformat it to a string is US format – MM/DD/YYYY

As I showed you can’t use [datetime] type accelerator for this as it expects the date string to be in US format.

A number of people pointed out that you can use the –Date parameter on Get-Date

£> $strUK = ’25/12/2014′
£> Get-Date -Date $strUK

25 December 2014 00:00:00

Now if you want that output as a string in US format

£> Get-Date -Date $strUK -Format “MM/dd/yyyy”

Use a variable to contain that data and you can work with it as you wish.

You need to be aware that using –Date on Get-Date is culture aware:

£> Get-Date -Date ’25/12/2014′

25 December 2014 00:00:00

£> Get-Date -Date ’12/25/2014′
Get-Date : Cannot bind parameter ‘Date’. Cannot convert value “12/25/2014” to type “System.DateTime”. Error: “String was not recognized as a valid DateTime.”
At line:1 char:16
+ Get-Date -Date ’12/25/2014′
+                ~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-Date], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.GetDateCommand

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

Leave a Reply

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

You are commenting using your 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