Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

The actual line in the PowerShell script that is desired is:

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

But the $TSDiff variable being used has time expressed as, without AM/PM:

20171023212800

This is a 24-hour format where 11 pm is represented by 23. It was retrieved using an FTP request which seems to only return 24 hour format strings without AM/PM.

Breaking this down, the following PowerShell command works:

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

But the following PowerShell command does not work:

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

The reason the second line doesn't work is clear; the hour digits are in 24-hour format, as in the $TSDiff listed at the beginning of this post.

Is there a simple way in PowerShell to convert the string 20171023212800 to 20171023092800PM?

like image 761
Alan Avatar asked Oct 19 '25 09:10

Alan


2 Answers

From 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.

[...]

While you are converting your datetime string to a 12-hour formatted string with hh in the format specifier, it will convert to a 24-hour string with HH in it like:

[datetime]::ParseExact("20171023212800",'yyyyMMddHHmmss',$null)
like image 146
Clijsters Avatar answered Oct 21 '25 13:10

Clijsters


Use:

# 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
}
like image 22
Esperento57 Avatar answered Oct 21 '25 12:10

Esperento57