format to datetime

This topic contains 7 replies, has 6 voices, and was last updated by  Olaf Soyk 9 months ago.

  • Author
    Posts
  • #62251

    jacobo
    Participant

    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.

  • #62263

    Ron
    Participant

    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.

  • #62265

    Don Jones
    Keymaster

    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.

  • #62280

    Richard Siddaway
    Moderator

    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

  • #62283

    Olaf Soyk
    Participant

    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])
  • #62374

    jacobo
    Participant

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

    cheers,
    Jacobo

  • #62380

    Peter Jurgens
    Participant

    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.

    • #62382

      Olaf Soyk
      Participant

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

      You're right. Both thumbs up. 😉

You must be logged in to reply to this topic.