You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何PowerShell中[datetime]隐式转[string]不遵循当前区域设置,与ToString()结果不同?

PowerShell中DateTime隐式转换与ToString()的格式差异问题

在PowerShell执行字符串拼接操作时,[datetime]类型会被自动隐式转换为[string]类型,但调用ToString()方法时采用当前区域设置,隐式转换却得到不同结果,具体示例如下:

PS C:\> 'now ' + (Get-Date).AddDays(-3)
now 06/10/2023 12:32:28
PS C:\> 'now ' + (Get-Date).AddDays(-3).ToString()
now 2023-06-10 12:32:47

PS C:\> $PSVersionTable.PSVersion.ToString()
7.3.4

差异原因

两者的核心区别在于遵循的格式化规则不同:

  • 隐式转换:PowerShell为保证输出一致性,对[datetime]这类常见类型定义了内置的默认转换规则,生成的字符串采用PowerShell预设的日期格式,不受.NET系统区域设置的直接影响。
  • ToString()方法调用:直接调用.NET原生的ToString()方法时,会严格遵循当前系统的区域文化(CultureInfo)设置,生成符合当前区域规范的日期字符串。

相关问题参考

原问题标题:Why is Powershell Write-Output Date Format not the System Setting?
中文翻译:为什么PowerShell的Write-Output日期格式不符合系统设置?

内容的提问来源于stack exchange,提问作者lit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 21:00:22