ParseExact - String was not recognized as a valid DateTime

John K. picture John K. · Mar 14, 2017 · Viewed 16.9k times · Source

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?

Answer

Matt picture Matt · Mar 14, 2017

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:\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

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)