header image

More on dates

Posted by: | December 30, 2014 Comments Off on 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"
12/25/2014

 

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

under: PowerShell Basics

Comments are closed.

Categories