2017-03-14 46 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) 
相關問題