BinaryPatrick
BinaryPatrick

Reputation: 512

[DateTime]::ParseExact throws exception

$dateParse = [datetime]::ParseExact("5/‎14/‎2008 ‏‎1:57", "M/d/yyyy h:m", $null)

results in

MethodInvocationException: C:\Users\89pmo\source\repos\File2Folder\RenameFile.ps1:9:3
Line |
   9 |          $dateParse = [datetime]::ParseExact("5/‎14/‎2008 ‏‎1:57", "M/ …
     |          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Exception calling "ParseExact" with "3" argument(s): "String '5/‎14/‎2008 ‏‎1:57' was not recognized as a valid DateTime."

I have also tried with M/d/yyyy h:mm, M/dd/yyyy h:m, and M/dd/yyyy h:mm to no avail..

Upvotes: 0

Views: 295

Answers (1)

AdminOfThings
AdminOfThings

Reputation: 25001

When copying and pasting your code into my console, I noticed extra unreadable characters (for ASCII anyway). Once those extra characters were removed, the original parsing worked.

# Original display in console
$dateParse = [datetime]::ParseExact("5/?14/?2008 ??1:57", "M/d/yyyy h:m", $null)
# This worked
$dateParse = [datetime]::ParseExact("5/14/2008 1:57", "M/d/yyyy h:m", $null)

Regarding including AM and PM in times, you will need to stick with h (12-hour format variant) for hours.

Upvotes: 1

Related Questions