KodeNode
KodeNode

Reputation: 45

How to perform awkward String to Date conversion?

I have a series of dates stored as strings in the following format:

06/23/20 10:05:59:557

and I need to convert them to dates for comparison purposes.

I tried this:

#$ldate2 = [datetime]::ParseExact($theDate,'MM/dd/yyyy HH:mm:ss:ffff',$null)

and

$ldate2 = [datetime]::ParseExact($theDate,'MM/dd/yyyy',$null)

But both cause the script to error.

Upvotes: 1

Views: 44

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 175085

The sample input in your post has a 2-digit year - for that you'll need the yy format specifier rather than yyyy:

[datetime]::ParseExact($theDate, 'MM/dd/yy HH:mm:ss:fff', $null)

If you want to convert it to a different format, parse it like above then use ToString() or Get-Date -Format to produce the target representation:

$datetime = [datetime]::ParseExact($theDate, 'MM/dd/yy HH:mm:ss:fff', $null)

$datetime.ToString('MM/dd/yyyy')
# or 
Get-Date $datetime -Format MM/dd/yyyy

Upvotes: 3

Related Questions