Chris Dents的回答已经涵盖了OP的问题,但由于这是谷歌上搜索“PowerShell将格式字符串转换为日期”的最高结果,我想提供一个不同的字符串示例。
如果像我一样,您得到的时间字符串如下:20190720170000.000000+000
需要注意的重要事项是,在使用[System.Management.ManagementDateTimeConverter]
时需要使用ToUniversalTime()
,否则您会得到相对于输入的偏移时间。
PS代码
cls
Write-Host "This example is for the 24hr clock with HH"
Write-Host "ToUniversalTime() must be used when using [System.Management.ManagementDateTimeConverter]"
$my_date_24hr_time = "20190720170000.000000+000"
$date_format = "yyyy-MM-dd HH:mm"
[System.Management.ManagementDateTimeConverter]::ToDateTime($my_date_24hr_time).ToUniversalTime();
[System.Management.ManagementDateTimeConverter]::ToDateTime($my_date_24hr_time).ToUniversalTime().ToSTring($date_format)
[datetime]::ParseExact($my_date_24hr_time,"yyyyMMddHHmmss.000000+000",$null).ToSTring($date_format)
Write-Host
Write-Host "-----------------------------"
Write-Host
Write-Host "This example is for the am pm clock with hh"
Write-Host "Again, ToUniversalTime() must be used when using [System.Management.ManagementDateTimeConverter]"
Write-Host
$my_date_ampm_time = "20190720110000.000000+000"
[System.Management.ManagementDateTimeConverter]::ToDateTime($my_date_ampm_time).ToUniversalTime();
[System.Management.ManagementDateTimeConverter]::ToDateTime($my_date_ampm_time).ToUniversalTime().ToSTring($date_format)
[datetime]::ParseExact($my_date_ampm_time,"yyyyMMddhhmmss.000000+000",$null).ToSTring($date_format)
输出
This example is for the 24hr clock with HH
ToUniversalTime() must be used when using [System.Management.ManagementDateTimeConverter]
20 July 2019 17:00:00
2019-07-20 17:00
2019-07-20 17:00
-----------------------------
This example is for the am pm clock with hh
Again, ToUniversalTime() must be used when using [System.Management.ManagementDateTimeConverter]
20 July 2019 11:00:00
2019-07-20 11:00
2019-07-20 11:00
Microsoft文档关于[Management.ManagementDateTimeConverter]
:
https://learn.microsoft.com/zh-cn/dotnet/api/system.management.managementdatetimeconverter?view=dotnet-plat-ext-3.1
Jul-16
,那么你为什么要用yyyy-MM-dd
来解析它,而不是MMM-dd
?你把这个和将字符串格式化为yyyy-MM-dd
混淆了。 - Jeroen Mostert