format to datetime

Welcome Forums General PowerShell Q&A format to datetime

This topic contains 7 replies, has 6 voices, and was last updated by

 
Participant
1 year, 10 months ago.

  • Author
    Posts
  • #62251

    Participant
    Points: 0
    Rank: Member

    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
    Points: 0
    Rank: Member

    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

    Keymaster
    Points: 1,673
    Helping HandTeam Member
    Rank: Community Hero

    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

    Participant
    Points: 0
    Rank: Member

    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

    Participant
    Points: 246
    Helping Hand
    Rank: 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

    Participant
    Points: 0
    Rank: Member

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

    cheers,
    Jacobo

  • #62380

    Participant
    Points: 51
    Rank: Member

    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

      Participant
      Points: 246
      Helping Hand
      Rank: Participant

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

      You're right. Both thumbs up. 😉

The topic ‘format to datetime’ is closed to new replies.