0

Today I met a problem with the conversion of this type of string "8/3/2020 10:29:33 AM" which I need to convert to date format.

I try this type of command and get an error every time:

$PwdExpiracy = "8/3/2020 10:29:33 AM"
$date = [datetime]::ParseExact($PwdExpiracy,'MM/dd/yyyy HH:mm:ss tt',$null)

The error is :

Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."
Au caractère Ligne:1 : 1
+ $date = [datetime]::ParseExact($PwdExpiracy,'MM/dd/yyyy HH:mm:ss tt',$nu ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : FormatException

Could you help me with this ? That would be very kind of you!

2 Answers 2

3

You're using format specifiers for dates with leading zeroes and 24-hour time - change to the following:

$date = [datetime]::ParseExact($PwdExpiracy, 'M/d/yyyy hh:mm:ss tt', $null)
  • M is the month without leading zeroes
  • d is the day without leading zeroes
  • hh is the hour in 12-hour time (AM/PM)

If you still receive "String was not recognized as a valid DateTime.", try forcing ParseExact() to use the InvariantCulture (roughly equivalent to en-US locale), and it should accept it:

$date = [datetime]::ParseExact($PwdExpiracy, 'M/d/yyyy hh:mm:ss tt', [cultureinfo]::InvariantCulture)
Sign up to request clarification or add additional context in comments.

Comments

0

Mathias R. Jessen said in a comment:

The exact same "String was not recognized as a valid DateTime.".

Can you try:

[datetime]::ParseExact($PwdExpiracy,'M/d/yyyy hh:mm:ss tt',[cultureinfo]::InvariantCulture)

which worked for me.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.