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

如何指定[datetime]/Get-Date按英式而非美式解析日期时间字符串?

如何为PowerShell的Get-Date和[datetime]类型指定日期字符串解析规则

现象差异原因

Get-Date "28/05/2023 15:05:29"能正常解析,而[datetime] "28/05/2023 15:05:29"报错,核心是两者的解析逻辑不同:

  • Get-Date解析字符串时会自动适配当前系统的区域设置(比如英式dd/MM/yyyy格式),当系统区域为英国格式时可正常解析。
  • [datetime]强制转换依赖.NET默认解析规则,默认遵循当前线程的文化设置,若字符串格式与默认文化不匹配则抛出错误。

为[datetime]指定解析规则

不要直接用强制转换,改用.NET的[datetime]::ParseExact()或[datetime]::TryParseExact()方法,手动指定格式和文化:

单格式解析

$dateString = "28/05/2023 15:05:29"
# 定义英式日期时间格式
$format = "dd/MM/yyyy HH:mm:ss"
# 指定英式文化
$culture = [System.Globalization.CultureInfo]::GetCultureInfo("en-GB")
# 解析为datetime对象
$dateObject = [datetime]::ParseExact($dateString, $format, $culture)

多格式兼容解析

如果需要兼容多种可能的日期格式,可传入格式数组:

$dateString = "28-05-2023 15:05:29"
$formats = @("dd/MM/yyyy HH:mm:ss", "dd-MM-yyyy HH:mm:ss")
$culture = [System.Globalization.CultureInfo]::GetCultureInfo("en-GB")
$dateObject = [datetime]::ParseExact($dateString, $formats, $culture, [System.Globalization.DateTimeStyles]::None)

为Get-Date指定解析规则

Get-Date没有直接设置解析格式的参数,可通过以下两种方式实现:

方法1:临时切换线程文化

# 保存当前文化设置
$originalCulture = [System.Threading.Thread]::CurrentThread.CurrentCulture
# 切换为英式文化
[System.Threading.Thread]::CurrentThread.CurrentCulture = [System.Globalization.CultureInfo]::GetCultureInfo("en-GB")
# 按英式规则解析字符串
$dateObject = Get-Date "28/05/2023 15:05:29"
# 恢复原文化设置
[System.Threading.Thread]::CurrentThread.CurrentCulture = $originalCulture

方法2:先手动解析再传入Get-Date

先通过ParseExact解析为datetime对象,再传给Get-Date(两者返回的对象类型一致,此方法更稳妥):

$dateString = "28/05/2023 15:05:29"
$dateObject = [datetime]::ParseExact($dateString, "dd/MM/yyyy HH:mm:ss", [System.Globalization.CultureInfo]::GetCultureInfo("en-GB"))
$getDateResult = Get-Date $dateObject

总结

  • [datetime]强制转换不支持直接指定解析规则,必须使用.NET的ParseExact/TryParseExact方法手动定义格式和文化。
  • Get-Date依赖系统/线程文化设置,可通过临时切换文化或先手动解析的方式实现指定规则的解析。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 10:33:22