2017-03-14 47 views
0

我想字符串变量转换为日期时间格式:ParseExact - 字符串未被识别为有效的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

,当我把“清洁日”,而不是变量,它工作正常。

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

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

+0

[这是什么在PowerShell中ParseExact代码的问题(// stackoverflow.com/q/17940647) – wOxxOm

+2

什么是'$ tempdate'的类型和价值? –

+2

除非我们更多地了解'$ tempdate',否则无法帮助您。 wOxxOm的链接问题有帮助吗?什么是当前类型? '$ tempdate.GetType()。Fullname'。是否有前导或尾随空格? '''$ tempdate'“' – Matt

回答

1

当我把'干净的日期'而不是变量时它工作正常。

这告诉我你的$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) 
相关问题