DateTime Casts are Language Primitives

Tue, Jan 13, 2009 2-minute read

One thing that sometimes comes as a surprise (most recently as a comment on the PowerShell blog) is that DateTime casts are always parsed in the en-US DateTime format:

Casting to a DateTime object doesn’t respect the current culture of the thread. For example:

> [Threading.Thread]::CurrentThread.CurrentCulture

LCID  Name

-—  —-

2057  en-GB

> [DateTime] “01/02/03”

02 January 2003

> # Note US date interpretation.

This is an explicit design goal.

To prevent subtle internationalization issues from popping into your scripts, PowerShell treats “[DateTime] ‘11/26/2007’” (a date constant) like a language feature – just as it does [Double] 10.5 (a numeric constant.) Not all cultures use the decimal point as the fractions separator, but programming languages standardize on it. Not all cultures use the en-US DateTime format, resulting in millions of internationalization bugs when people don’t consider the impact of having their software run in those cultures.

Imagine a random script that you find on the internet. It was probably written on a system that uses a different culture than you or I. For the script to run correctly our machines, the author needs to write in a culturally-sensitive way:

  1. The approach taken by traditional software development for internationalization:

$date = New-Object System.DateTime 2007,11,27,17,56,00

or (an imagined PowerShell syntax)

$date = [DateTime->pt-PT] “terça-feira, 27 de Novembro de 2007 9:34:50”

  1. An approach that assumes a specific culture, which is the approach PowerShell takes:

$date = [DateTime] “11/27/2007 5:56:00 pm”

Approach #2 is much more user-friendly, as it minimizes what you need to remember. In approach #1, you always need to remember to specify your locale when you create the DateTime. In approach #2, you always need to remember to use the en-US format (as you already do when writing floating-point constants.)

The additional benefit of assuming a specific culture is that you are protected from people that do NOT write the script in a culturally-sensitive way. While some advanced scripters might be able to understand approach #1, most scripters (and even professional software developers) do not. History has shown us that software not explicitly TESTED for internationalization fails spectacularly. I don’t mean “written for international markets,” I mean TESTED for them.

When an admin bashes together a script because their hair is on fire, and then wants to share it later – testing for other regions is not high on the list of things to do.