将字符串转换为 PowerShell DateTime
Convert string to PowerShell DateTime
我有以下字符串:"02-06-2018 16:25:28"
。我需要将其转换为 DateTime
对象。我试过这样做:
[DateTime]::ParseExact('02-06-2018 16:25:28', 'dd-MM-yyyy hh:mm:ss', $null)
但是没有用:
String was not recognized as a valid DateTime.
有没有[DateTime]::ParseExact
以外的函数支持解析dd-MM-yyyy hh:mm:ss
这种格式的字符串?
我正在使用 PowerShell v5.1。
24 小时制需要 HH
。 hh
用于 12 小时制,不识别第 16 小时。我还建议使用 InvariantCulture
而不是 $null
,因为后者有时不起作用。
$culture = [Globalization.CultureInfo]::InvariantCulture
[DateTime]::ParseExact('02-06-2018 16:25:28', 'MM-dd-yyyy HH:mm:ss', $culture)
您也可以将 date/time 字符串传递给 Get-Date
,它会为您转换它们:例如 get-date "02-06-2018 16:25:28"
。这将 return 一个 System.DateTime 对象,并且可以通过 powershell 以通常的方式进行操作。
我有以下字符串:"02-06-2018 16:25:28"
。我需要将其转换为 DateTime
对象。我试过这样做:
[DateTime]::ParseExact('02-06-2018 16:25:28', 'dd-MM-yyyy hh:mm:ss', $null)
但是没有用:
String was not recognized as a valid DateTime.
有没有[DateTime]::ParseExact
以外的函数支持解析dd-MM-yyyy hh:mm:ss
这种格式的字符串?
我正在使用 PowerShell v5.1。
24 小时制需要 HH
。 hh
用于 12 小时制,不识别第 16 小时。我还建议使用 InvariantCulture
而不是 $null
,因为后者有时不起作用。
$culture = [Globalization.CultureInfo]::InvariantCulture
[DateTime]::ParseExact('02-06-2018 16:25:28', 'MM-dd-yyyy HH:mm:ss', $culture)
您也可以将 date/time 字符串传递给 Get-Date
,它会为您转换它们:例如 get-date "02-06-2018 16:25:28"
。这将 return 一个 System.DateTime 对象,并且可以通过 powershell 以通常的方式进行操作。