[英]Convert String to Date in Powershell
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.今天我遇到了转换这种类型的字符串“8/3/2020 10:29:33 AM”的问题,我需要将其转换为日期格式。
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:您正在对带有前导零和 24 小时时间的日期使用格式说明符 - 更改为以下内容:
$date = [datetime]::ParseExact($PwdExpiracy, 'M/d/yyyy hh:mm:ss tt', $null)
M
is the month without leading zeroes M
是没有前导零的月份d
is the day without leading zeroes d
是没有前导零的日子hh
is the hour in 12-hour time ( AM
/ PM
) hh
是 12 小时制中的小时 ( AM
/ PM
) If you still receive "String was not recognized as a valid DateTime."
如果您仍然收到
"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: ,尝试强制
ParseExact()
使用InvariantCulture
(大致相当于en-US
语言环境),它应该接受它:
$date = [datetime]::ParseExact($PwdExpiracy, 'M/d/yyyy hh:mm:ss tt', [cultureinfo]::InvariantCulture)
Mathias R.马蒂亚斯 R。 Jessen said in a comment :
杰森在评论中说:
The exact same
"String was not recognized as a valid DateTime."
完全相同的
"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.这对我有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.