Why does PowerShell always use US culture when casting to DateTime?

前端 未结 2 1417
时光说笑
时光说笑 2020-12-11 15:29

When trying to read a CSV yesterday, I noticed that PowerShell seems to always assume US date format when using [datetime]\"date\".

My regional

相关标签:
2条回答
  • 2020-12-11 15:35

    You can force the culture for a single command if needed:

    PS C:\> [System.Threading.Thread]::CurrentThread.CurrentUICulture = "en-US" ; [System.Threading.Thread]::CurrentThread.CurrentCulture = "en-US"; [DateTime]::Parse("12/10/2012")
    
    Monday, December 10, 2012 12:00:00 AM
    
    PS C:\> [System.Threading.Thread]::CurrentThread.CurrentUICulture = "en-GB" ; [System.Threading.Thread]::CurrentThread.CurrentCulture = "en-GB"; [DateTime]::Parse("12/10/2012")
    
    12 October 2012 00:00:00
    
    0 讨论(0)
  • 2020-12-11 15:47

    It is a deliberate decision. When casting a string to a DateTime you can use either the braindead US format or ISO 8601 – [datetime]'2012-10-12' works just fine and is much nicer to read.

    The reason that this is limited and restricted is that scripts should not have a dependency on the current culture, at least for literals and quasi-literals (like casted strings). This is a major problem in writing robust batch files and you certainly don't want the same problems in PowerShell.

    Lee Holmes has an explanation, which could be considered semi-official, as he is/was on the PowerShell team at MS:

    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.

    What Lee forgets to mention is what I wrote before, that the much more sensible ISO 8601 format works as well.

    No documentation of this exists in either the PowerShell documentation or the Language Specification (v2), sadly. However, there is very little evidence that points to this being a bug.

    0 讨论(0)
提交回复
热议问题