Search code examples
powershelldatetime

Display [datetime] object in 24 hour format


I have some code that checks for a valid date, simple example:

[datetime]::ParseExact(
    '201809222130',
    'yyyyMMddHHmm',
    [System.Globalization.CultureInfo]::InvariantCulture
)

This outputs:

Saturday, September 22, 2018, 9:30:00 PM

I'm trying to display the hour in 24h format, desired output:

Saturday, September 22, 2018, 21:30:00 PM

It is possible to display 24h format using the Get-Date Cmdlet, e.g.: Get-Date -UFormat %R, but I can't use this when creating a [datetime] object.

How can I display 24h format?


Solution

  • There isn't any reason you can't use Get-Date with the [datetime] object your code creates. For example:

    $d = [datetime]::ParseExact(
        '201809222130',
        'yyyyMMddHHmm',
        [System.Globalization.CultureInfo]::InvariantCulture
    )
    
    Get-Date $d -UFormat %R
    

    You could also use the .ToShortTimeString() method:

    $d.ToShortTimeString()
    

    Or .ToString and specify the tokens:

    $d.ToString('HH:mm')