Reputation: 141
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!
Upvotes: 0
Views: 410
Reputation: 175085
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 zeroesd
is the day without leading zeroeshh
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)
Upvotes: 3
Reputation: 141
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.
Upvotes: 0