Monthly Archive

Categories

Cultured Dates

In this post - http://richardsiddaway.spaces.live.com/default.aspx?_c01_BlogPart=blogentry&_c=BlogPart&handle=cns!43CFA46A74CF3E96!2007 – I talked about the way date strings had to be formatted when we were creating datetime objects -

[datetime]”mm/dd/yyyyy”

I have since discovered its a little bit more complicated than that. 

If we start by examining the culture on my machine.

PS> $host | Select *culture | fl

CurrentCulture   : en-GB
CurrentUICulture : en-US

Notice they are not the same – en-US means I have to use American (US) English for UI based activities but the culture of the machine is set to en-GB which is UK English. To recap the previous post if I am using [datetime] to create the object I need to follow the UICulture – that is use a mm//dd/yyyy format as shown

PS> [datetime]"25/12/2009"
Cannot convert value "25/12/2009" to type "System.DateTime". Error: "String was not recognized as a valid DateTime."
At line:1 char:11
+ [datetime] <<<< "25/12/2009"
    + CategoryInfo          : NotSpecified: (:) [], RuntimeException
    + FullyQualifiedErrorId : RuntimeException

PS> [datetime]"12/25/2009"

25 December 2009 00:00:00

If I use get-date to create the object – it doesn’t work using the same rules

PS> Get-Date -Date "12/25/2009"
Get-Date : Cannot bind parameter 'Date'. Cannot convert value "12/25/2009" to type "System.DateTime". Error: "String was not recognized as a valid DateTime."
At line:1 char:15
+ Get-Date -Date <<<<  "12/25/2009"
    + CategoryInfo          : InvalidArgument: (:) [Get-Date], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.GetDateCommand

It does work with the CurrentCulture format – ie UK format of dd/mm/yyyyy

PS> Get-Date -Date "25/12/2009"

25 December 2009 00:00:00

PS> Get-Date "25/12/2009"

25 December 2009 00:00:00

PS> Get-Date 25/12/2009

25 December 2009 00:00:00

Just to complete the set you can also create dates like this

PS> New-Object -TypeName System.DateTime -ArgumentList 2009,12,25

25 December 2009 00:00:00

Where we use year, month and day as the 3 arguments – this ignores culture completely.

If you are using PowerShell with a machine set for US English [datetime] and get-date work in an identical manner – otherwise be aware that the machine culture will affect how get-date works in this instance.

Technorati Tags: PowerShell,Dates

Leave a Reply