none
How can I extract dates from a funky filename (date's in name as yyyyMMdd)

    Question

  • Here's an example, but, the last line doesn't convert to [DateTime].

    $pattern = "(?<text>.*)(?<date>\d{8})(?<text2>.*)"
    "a_12345678_at.txt" -match $pattern | Out-Null
    ([DateTime] ($matches.date)).ToString('MM-dd-yyyy')

    Throws this error:

    Cannot convert value "20120224" to type "System.DateTime". Error: "String was not recognized as a valid DateTime."
    At line:1 char:23
    + ([DateTime] ($matches. <<<< date)).ToString('MM-dd-yyyy')   
     + CategoryInfo          : NotSpecified: (:) [], RuntimeException   
     + FullyQualifiedErrorId : RuntimeException
    See mjolinor, I am using regexes... :)  I even threw in some group names.


    Monday, February 27, 2012 10:43 PM

Answers

  • PS >  [DateTime]::ParseExact("20120224","yyyyMMdd",$null).ToString('MM-dd-yyyy')
    02-24-2012

    • Marked as answer by Will Steele Monday, February 27, 2012 10:49 PM
    Monday, February 27, 2012 10:47 PM
  • $datestring = '20120224'
    ([datetime]::parseexact($datestring,'yyyyMMdd',$nul)).ToString('MM-dd-yyyy')
    02-24-2012


    [string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

    • Marked as answer by Will Steele Monday, February 27, 2012 10:51 PM
    Monday, February 27, 2012 10:50 PM

All replies

  • PS >  [DateTime]::ParseExact("20120224","yyyyMMdd",$null).ToString('MM-dd-yyyy')
    02-24-2012

    • Marked as answer by Will Steele Monday, February 27, 2012 10:49 PM
    Monday, February 27, 2012 10:47 PM
  • Doh. I'm going to have to tattoo [DateTime]::ParseExact on my hands.  Thanks Kazun.
    Monday, February 27, 2012 10:49 PM
  • $datestring = '20120224'
    ([datetime]::parseexact($datestring,'yyyyMMdd',$nul)).ToString('MM-dd-yyyy')
    02-24-2012


    [string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

    • Marked as answer by Will Steele Monday, February 27, 2012 10:51 PM
    Monday, February 27, 2012 10:50 PM
  • I'm going to have to learn to type faster, or give up.

    [string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

    Monday, February 27, 2012 10:51 PM
  • I'll give you points since you were working on it and the answer's right. : )  Thanks both guys.
    Monday, February 27, 2012 10:52 PM
  • # the unorthodox way
    '20120224' -replace '(....)(..)(..)', '$2/$3/$1' -as [datetime]
    '20120224' -replace '(....)(..)(..)', '$2-$3-$1'
    
    Tuesday, February 28, 2012 5:04 AM