4

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.

2 Answers 2

9

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Ah, that was it. Thanks a lot. (btw, edit your answer, you wrote 'hh', not 'HH' in the code.
@RonaDona Yeah, thanks for the heads up. BTW, your example timestamp looks like it was from today. If that's the case you also need to change dd-MM-yyyy to MM-dd-yyyy.
2

You can pass date/time strings to Get-Date as well, it will convert them for you: get-date "02-06-2018 16:25:28" for example. This will return a System.DateTime object and can be manipulated in the usual ways by powershell.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.