Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to PowerShell DateTime

I have the following string: "02-06-2018 16:25:28". I need to convert it to a DateTime object. I tried doing this:

[DateTime]::ParseExact('02-06-2018 16:25:28', 'dd-MM-yyyy hh:mm:ss', $null)

But it did not work:

String was not recognized as a valid DateTime.

Is there another function other than [DateTime]::ParseExact that supports parsing the string in this fomat dd-MM-yyyy hh:mm:ss?

I'm using PowerShell v5.1.

like image 468
RonaDona Avatar asked Dec 24 '22 10:12

RonaDona


1 Answers

You need HH for a 24-hour clock. hh is for a 12-hour clock, which doesn't recognize a 16th hour. I would also recommend using InvariantCulture instead of $null, as the latter sometimes won't work.

$culture = [Globalization.CultureInfo]::InvariantCulture
[DateTime]::ParseExact('02-06-2018 16:25:28', 'MM-dd-yyyy HH:mm:ss', $culture)
like image 52
Ansgar Wiechers Avatar answered Jan 15 '23 11:01

Ansgar Wiechers