首页 > 解决方案 > 在 Powershell 中使用缩写的工作日名称解析 DateTime

问题描述

我从 api 获得以下格式的日期:

   Mon Apr 29 14:40:17 2019

我尝试使用以下命令将其解析为有效的 powershell 日期:

  $test = [DateTime]::ParseExact("Mon Apr 29 14:40:03 2019", "ddd MMM dd HH:mm:ss yyyy",$null)

Powershell 返回“使用“3”个参数调用“ParseExact”的异常:“字符串未被识别为有效的日期时间。”

似乎由于缩写的工作日格式而出现问题。如果我删除“Mon”和“ddd”,则解析有效。

有关格式说明符的信息来自:https ://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings#dddSpecifier

任何人都知道是什么导致了错误?

标签: powershelldatetimeparsing

解决方案


Replacing $null with [System.Globalization.CultureInfo]::InvariantCulture solved the problem.

The working code is:

    $test = [DateTime]::ParseExact("Mon Apr 29 14:40:03 2019", "ddd MMM dd HH:mm:ss yyyy",[System.Globalization.CultureInfo]::InvariantCulture)

推荐阅读