ParseExact - 字符串未被识别为有效的日期时间

ParseExact - String was not recognized as a valid DateTime

我正在尝试将字符串变量转换为日期时间格式:

[DateTime]::ParseExact($tempdate, 'dd.MM.yyyy', [CultureInfo]::InvariantCulture).ToString('yyMMdd')

$tempdate 包含从 Excel 文件中获得的 dd.MM.yyyy 格式的日期。

很遗憾,我收到错误消息:

Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a
valid DateTime."
At line:1 char:1
+ [DateTime]::ParseExact($tempdate, 'dd.MM.yyyy', [CultureInfo]::Invaria ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : FormatException

当我输入 'clean date' 而不是变量时它工作正常。

[DateTime]::ParseExact('13.03.2017', 'dd.MM.yyyy', [CultureInfo]::InvariantCulture).ToString('yyMMdd')

这个变量有什么问题,或者我怎样才能以其他方式将它转换为日期时间?

It works fine when I put 'clean date' instead of variable.

这告诉我您的 $tempdate 有问题,首先它应该是一个字符串,但您可能会遇到前导或尾随空格的问题。考虑以下。

PS C:\Users\Bagel> [DateTime]::ParseExact(' 13.03.2017 ', 'dd.MM.yyyy',[CultureInfo]::InvariantCulture)
Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."
At line:1 char:1
+ [DateTime]::ParseExact(' 13.03.2017 ', 'dd.MM.yyyy',[CultureInfo]::In ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : FormatException

因此,正如我们在评论中发现的那样,这似乎是您的问题。假设您无法控制 $tempdate 的填充方式,一个简单的 .trim() 应该可以为您处理这个问题(如果您控制了,您应该首先解决该问题)。

[DateTime]::ParseExact(' 13.03.2017 '.Trim(), 'dd.MM.yyyy',[CultureInfo]::InvariantCulture)