Search code examples
powershellpowershell-3.0

How to convert string to date in 24 hour format in powershell?


I am having a string which contains 24 hr format.

I am trying to convert it to 24hrs format but it is not changing. below is my code.

$fromtime = '2018-03-28,23:37:50'
[datetime]$fromtime24hrFormat = ([datetime]$fromtime).ToString("yyyy-MM-dd,HH:mm:ss")
$fromtime24hrFormat

Wednesday, March 28, 2018 11:37:50 PM

It shows in PM which is correct. But is it not possible to show it in 24 hr format?


Solution

  • You're so close!

    $fromtime = '2018-03-28,23:37:50'
    [datetime]$fromtime24hrFormat = ([datetime]$fromtime)
    $fromtime24hrFormat.ToString("yyyy-MM-dd,HH:mm:ss")
    

    The problem is that your last line was effectively just dumping the datetime object to the output; which will use a default formatting.