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

4

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

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

$tempdate 包含一个格式为 dd.MM.yyyy 的日期,该日期是从 Excel 文件中获取的。

遗憾的是,我收到了错误消息:

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

当我将“干净日期”替换变量时,它可以正常工作。

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

这个变量有什么问题,或者我该如何以其他方式将其转换为日期时间格式?

2
$tempdate 的类型和值是什么? - Ansgar Wiechers
2
除非我们了解$tempdate的更多信息,否则无法帮助您。wOxxOm的链接问题是否有所帮助?当前类型是什么?$tempdate.GetType().Fullname。是否有任何前导或尾随空格?"'$tempdate'" - Matt
@Matt - 感谢您的回答。字符串末尾有转义字符(下一行)。我将其删除,现在它可以正常工作了。顺便提一下,$tempdate是一个字符串,包含13.03.2017。当然,我需要以这种方式转换多个变量。问题已解决。 - John K.
1个回答

2

当我把“清除日期”代替变量时,它可以正常工作。

这告诉我您的$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

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接