1

I've been struggling with this for some time now and I've tried everything I could find but, have yet to be successful. I need to convert this string to a Powershell date object:

20180802 16:30:10

Everytime I try ParseExact, it's saying that it doesn't recognize the string as a valid date/time format.

2 Answers2

4

Following works perfectly:

[DateTime]::ParseExact('20180802 16:30:10', 'yyyyMMdd HH:mm:ss', [CultureInfo]::InvariantCulture)

I bet your problem is 24 hour format.

Paweł Dyl
  • 8,888
  • 1
  • 11
  • 27
0

Pawel Dyl's helpful answer is the correct and robust solution.

Just to offer a shortcut that may be of interest in similar situations where only a simple textual reformatting is needed in order for a [datetime] cast to recognize a string containing a date/time representation:

Transforming 20180802 16:30:10 to 2018-08-02 16:30:10 would work:

PS> [datetime] ('20180802 16:30:10' -replace '^(\d{4})(\d{2})', '$1-$2-')

Thursday, August 2, 2018 4:30:10 PM  # sample output on a US-English system

Note that a [datetime] cast in PowerShell uses the invariant culture, as PowerShell does in many contexts.

mklement0
  • 382,024
  • 64
  • 607
  • 775