Share via


Date and Time format with ParseExact

Question

Tuesday, September 25, 2012 9:36 PM

I have some dates and times in the following format:

"26/10/2013 9:11 AM"

This works fine:

$strtime = "26/10/2013 9:11"
([datetime]::ParseExact($strtime,”dd/MM/yyyy h:mm”,$null)).toshortdatestring()

...but this....

$strtime = "26/10/2013 9:11 AM"
([datetime]::ParseExact($strtime,”dd/MM/yyyy h:mm tt”,$null)).toshortdatestring()

...throws the following exception

Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."
At C:\Util\Powershell\Tester.ps1:6 char:24

  • ([datetime]::ParseExact <<<< ($strtime,”dd/MM/yyyy h:mm tt”,$null)).toshortdatestring()
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : DotNetMethodException

From what I've read "tt" represents AM or PM, so I can't see what I'm doing wrong.  Any thoughts?

Alexei

All replies (2)

Tuesday, September 25, 2012 9:54 PM ✅Answered

Your input string is not quite right...

$strtime = "26/10/2013 9:11 A.M."([datetime]::ParseExact($strtime,”dd/MM/yyyy h:mm tt”,$null)).toshortdatestring()

Note the A.M. instead of AM

Looks like it depends on your system regional settings.

English(US) seems to need AM instead of A.M. whereas my regional settings (and yours?) are the opposite.

Admiral Akbar says...


Tuesday, September 25, 2012 10:12 PM

Thanks, that works perfectly!

Alexei