Author Posts

January 20, 2017 at 3:47 pm

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.

January 20, 2017 at 4:43 pm

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.

January 20, 2017 at 5:10 pm

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.

January 20, 2017 at 8:18 pm

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

January 20, 2017 at 8:35 pm

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])

January 21, 2017 at 11:42 pm

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

cheers,
Jacobo

January 22, 2017 at 1:10 am

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.

January 22, 2017 at 1:20 am

I'm on mobile doing this from memory but I think I got everything right!

You're right. Both thumbs up. 😉