如何将 PowerShell 日期时间字符串从 24 小时格式转换为 12 小时格式?

How do I convert a PowerShell datetime string from 24 hour to 12 hour format?

PowerShell 脚本中所需的实际行是:

$tsd = [datetime]::ParseExact($TSDiff,'yyyyMMddhhmmsstt',$null)

但是正在使用的 $TSDiff 变量的时间表示为,没有 AM/PM:

20171023212800

这是一个 24 小时格式,其中晚上 11 点由 23 表示。它是使用 FTP 请求检索的,该请求似乎只有 return 24 小时格式字符串,没有 AM/PM .

将其分解,以下 PowerShell 命令有效:

[datetime]::ParseExact("20171023092800",'yyyyMMddhhmmss',$null)

但是下面的 PowerShell 命令不起作用:

[datetime]::ParseExact("20171023212800",'yyyyMMddhhmmss',$null)

第二行不起作用的原因很清楚;小时数字采用 24 小时格式,如 post.

开头列出的 $TSDiff

PowerShell 中是否有一种简单的方法可以将字符串 20171023212800 转换为 20171023092800PM

使用:

# Method 1. Use HH for 24-hour format like TessellatingHeckler proposes
[datetime]::ParseExact("20171023212800", 'yyyyMMddHHmmss', $null)


# Method 2. If you are not sure your string is
# date, use TryParse with the same format
[datetime]$dirDate = New-Object DateTime

if ([DateTime]::TryParseExact(
                  '20171023212800',
                  'yyyyMMddHHmmss',
                  [System.Globalization.CultureInfo]::InvariantCulture,
                  [System.Globalization.DateTimeStyles]::None,
                  [ref]$dirDate))
{
    $dirDate
}

来自Formatting Dates and Times

[...]

  • h, %h - The hour in a 12-hour clock. Single-digit hours will not have a leading zero. Specify %h if the format pattern is not combined with other format patterns.
  • hh - The hour in a 12-hour clock. Single-digit hours will have a leading zero.
  • H, %H - The hour in a 24-hour clock. Single-digit hours will not have a leading zero. Specify %H if the format pattern is not combined with other format patterns.
  • HH - The hour in a 24-hour clock. Single-digit hours will have a leading zero.

[...]

当您将日期时间字符串转换为格式说明符中带有 hh 的 12 小时制字符串时,它将转换为带有 HH 的 24 小时制字符串,例如:

[datetime]::ParseExact("20171023212800",'yyyyMMddHHmmss',$null)