Samselvaprabu
Samselvaprabu

Reputation: 18147

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?

Upvotes: 3

Views: 6997

Answers (2)

Frode F.
Frode F.

Reputation: 54881

Did you want to add AM/PM to the original input? Try:

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

2018-03-28,23:37:50 p.m.

"p.m." vs PM is caused by my Norwegian regional settings

Upvotes: 2

gvee
gvee

Reputation: 17161

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.

Upvotes: 4

Related Questions