gpt4 book ai didi

date - 为什么 PowerShell 在转换为 DateTime 时总是使用美国文化?

转载 作者:行者123 更新时间:2023-12-03 20:39:23 27 4
gpt4 key购买 nike

昨天尝试读取 CSV 时,我注意到 PowerShell 在使用 [datetime]"date" 时似乎总是假定美国日期格式。 .

我的区域设置都是正确的 , 和 [DateTime]::Parse("date")使用英国日期格式 (日/月/年)。

这是一个错误,还是一个深思熟虑的决定 ?如果是深思熟虑的决定,是否记录在任何地方?

PS D:\> [DateTime]"12/10/2012"
10 December 2012 00:00:00

PS D:\> [DateTime]::Parse("12/10/2012")
12 October 2012 00:00:00

(注意:在美国机器上,我希望这些对象是相同的,但在英国的机器上不是这样)。

注意:我不想更改格式(它是来自外部来源的文件),我不想在输出中格式化日期,我知道我可以使用 [DateTime]::Parse() .问题是以 ? 结尾的位:-)

最佳答案

这是一个深思熟虑的决定。将字符串转换为 DateTime 时您可以使用braindead US 格式 ISO 8601 – [datetime]'2012-10-12'工作得很好,读起来要好得多。

这是有限的和受限的原因是脚本不应该依赖于当前的文化,至少对于文字和准文字(如转换字符串)。这是编写健壮的批处理文件的一个主要问题,您当然不希望 PowerShell 中出现相同的问题。

Lee Holmes has an explanation ,这可以被认为是半官方的,因为他是/曾经是 MS PowerShell 团队的成员:

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.



Lee 忘记提及的是我之前写过的内容,即更合理的 ISO 8601 格式也适用。

遗憾的是,PowerShell 文档或语言规范 (v2) 中都没有这方面的文档。但是,很少有证据表明这是一个错误。

关于date - 为什么 PowerShell 在转换为 DateTime 时总是使用美国文化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14359053/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com