Get date from text line

Welcome Forums General PowerShell Q&A Get date from text line

Viewing 1 reply thread
  • Author
    Posts
    • #211779
      Participant
      Topics: 5
      Replies: 9
      Points: 41
      Rank: Member

      Hi, I would like to get date from a text line.

      text = “some.test.20.01.05.xcddcd.dcdcdcdc.sdsdsd”

      [datetime]::ParseExact($text, “y.m.d”, $null)

      If successful i should have date in following format 05 Jan 2020

      I try above code but i get a error.

      Exception calling “ParseExact” with “3” argument(s): “String was not recognized as a valid DateTime.”
      At line:7 char:1
      + [datetime]::ParseExact($text,’y.m.d’,[cultureinfo]::InvariantCulture) …
      + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
      + FullyQualifiedErrorId : FormatException

    • #211785
      Participant
      Topics: 4
      Replies: 1950
      Points: 4,423
      Helping Hand
      Rank: Community Hero

      You will have to cut of the pure date string from the surrounding text. Assuming your input text has always the same format something like this would be an easy way to do this.

      $imputText = "some.test.20.01.05.xcddcd.dcdcdcdc.sdsdsd"
      $splittedText = ($imputText -split '\.')[2..4] -join '.'
      [datetime]::ParseExact($splittedText, "y.m.d", $null)

      When you post code or sample data or console output like error messages you should format this as code using the code tags “PRE“. Thanks.

      You might (re-)read the instructions contained in the very first post on top of the list of this forum: Read Me Before Posting! You’ll be Glad You Did!

Viewing 1 reply thread
  • You must be logged in to reply to this topic.