在 PowerShell 中通过 ParseExact 解析日期时间
在 PowerShell 上处理日期时,有时你需要将日期字符串转换为 DateTime
对象。你不能使用日期字符串来执行 DateTime 操作;你将需要 DateTime
对象。
本教程将教你在 PowerShell 中解析字符串并将其转换为 DateTime 格式。
在 PowerShell 中使用 ParseExact
方法来解析 DateTime
DateTime
类的 ParseExact
方法将日期和时间字符串转换为 DateTime 格式。日期和时间字符串模式的格式必须与 DateTime
对象的指定格式匹配。
下面的示例使用 ParseExact
方法将日期字符串转换为 DateTime
对象。
$strDate = '2022/06/11'
[DateTime]::ParseExact($strDate, 'yyyy/MM/dd', $null)
在上述脚本中,日期字符串存储在变量 $strDate
中。然后将其传递给 ParseExact
方法,后跟 DateTime 格式,该格式与日期字符串的模式相匹配。
输出:
11 June 2022 00:00:00
你可以将转换后的 DateTime 格式存储在变量中,并使用 GetType()
方法检查数据类型。
$strDate = '2022/06/11'
$newDate=[Datetime]::ParseExact($strDate, 'yyyy/MM/dd', $null)
$newDate.GetType()
输出:
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True DateTime System.ValueType
在 PowerShell 中使用显式类型转换解析 DateTime
你还可以在 PowerShell 中将日期和时间字符串转换为 DateTime
格式。
使用此语法,你可以将字符串强制转换为 DateTime
对象。
[DateTime]string
以下示例使用强制转换表达式将日期和时间的字符串表示形式转换为 DateTime
对象。
$strDate = "2022-06-11 09:22:40"
[DateTime]$strDate
输出:
11 June 2022 09:22:40
使用 DateTime
对象,你应该能够执行任何 DateTime 操作。我们希望本教程能帮助你了解如何在 PowerShell 中将字符串转换为 DateTime 格式。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。