Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

powershell - ParseExact - String was not recognized as a valid DateTime

I'm trying to convert string variable to datetime format:

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

$tempdate contains date in format dd.MM.yyyy which was obtained from an Excel file.

Unfortunately I'm getting error message:

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

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

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

What is wrong with this variable or how can I convert it to datetime in other way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

That tells me something is wrong with your $tempdate first and foremost it should be a string but you could have an issue with leading or trailing whitespace. Consider the following.

PS C:UsersBagel> [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

So, as we have discovered in comments, this appears to be your problem. A simple .trim() should handle this for you assuming you do not have control over how $tempdate is populated (If you do you should fix the issue there first).

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...