format to datetime

Hello,

I have a external command generating an output.
“Sep 12 23:59:59 2016 GMT”

I have been trying to parse it as a datetime format but I am stuck.
Any help is appreciated.

Regards,
Jacobo.

Here is an ugly solution, maybe someone else has something better.

$m=[regex]::Matches("Sep 12 23:59:59 2016 GMT","(\w+ \d+) (\d+:\d+:\d+) (\d+) (\w+)")
get-date ($m[0].groups[1].value +  ' ' + $m[0].groups[3].value + ' ' + $m[0].groups[2].value + ' ' + $m[0].groups[4].value)

This will come back converted to local time. If you don’t want that, leave off the time zone.

Huh. I’d have thought just [datetime]“Sep 12 23:59:59 2016 GMT” woulda done it. I’ll have to look and see if one of the System.DateTime constructors offers something more elegant.

The year is in the wrong place. You need

[datetime]“Sep 12 2016 23:59:59 GMT”

Also can only specify the time to be local or UTC/GMT

The shortes I found:

‘Sep 12 23:59:59 2016 GMT’ -match ‘(\w+\s\d+\s+)((\d+:){2}\d+\s)(\d{4}\s\w{3})’
Get-Date $($Matches[2] + $Matches[1] + $Matches[4])

thanks everyone for your replies, and Olaf for the regex which works perfectly.

cheers,
Jacobo

The ParseExact method of the system.datetime class is useful when working with an oddly formatted date time string:

[datetime]::ParseExact(“Sep 12 23:59:59 2016 GMT”,“MMM dd HH:mm:ss yyyy GMT”,[system.globalization.cultureinfo]::InvariantCulture)

I’m on mobile doing this from memory but I think I got everything right! If not let me know and I’ll confirm when in front of a PC.

I'm on mobile doing this from memory but I think I got everything right!
You're right. Both thumbs up. ;-)