4

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?

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
John K.
  • 43
  • 1
  • 1
  • 3
  • [What's the issue with this ParseExact code in PowerShell](//stackoverflow.com/q/17940647) – wOxxOm Mar 14 '17 at 11:39
  • 2
    What is the type and value of `$tempdate`? – Ansgar Wiechers Mar 14 '17 at 11:43
  • 2
    Can't help you unless we know more about `$tempdate`. Does the linked question from wOxxOm help? What is the current type? `$tempdate.GetType().Fullname`. Are there any leading or trailing spaces? `"'$tempdate'"` – Matt Mar 14 '17 at 11:44
  • @Matt - thank you for your answer. There was escape character in the end of the string(next line). I removed it and it works. FYI - $tempdate is a string and contains 13.03.2017. Of course I need to convert multiple variables in this way. Problem solved. – John K. Mar 14 '17 at 12:14

1 Answers1

2

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)
Matt
  • 45,022
  • 8
  • 78
  • 119