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!
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)
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.