Get date from text line

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

Viewing 1 reply thread
  • Author
    • #211779
      Topics: 7
      Replies: 9
      Points: 53
      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
      Topics: 5
      Replies: 2368
      Points: 5,987
      Helping Hand
      Rank: Community MVP

      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
  • The topic ‘Get date from text line’ is closed to new replies.