ParseExact with odd date/time format as input fails

Hi,

I am trying to convert a odd date/time string with the format “MMM dd, HH:mm zzz” into a [datetime] datatype, so I can convert it to my time zone; and I am struggling with ParseExtract.

The string (example “Feb 14, 14:37 PST”) is helpfully provided from the data feed without the year; but it is the current year.

I have tried pre-pending the current year into the input string; but that hasn’t worked.

This is where I am at code wise:

$InputString = "Feb 14, 14:37 PST"
$CurrentYear = Get-Date -UFormat %Y
$InputStringWithYear = $CurrentYear + " " + $InputString  
$OutputDateTime = [datetime]::ParseExact($InputStringWithYear, "yyyy MMM dd, HH:mm zzz", $null)

and this is the error:

Exception calling "ParseExact" with "3" argument(s): "String was not recognized as a valid DateTime."
At line:4 char:1
+ $OutputDateTime = [datetime]::ParseExact($InputStringWithYear, "yyyy  ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : FormatException

Would appreciate it if anyone can help or give me an alternative approach to try.

I thought this would be straightforward :rofl:

Cheers
Pin.

According to this stackoverflow thread

you will have to replace the time zone abbreviation with its offset to get the correct result.

So if your time zone is allways PST and if that stands for Pacific Standard Time you could do something like this:

$InputString = 'Feb 14, 14:37 PST'
$InputStringWithOffset = $InputString -replace 'PST','-8'
[datetime]::ParseExact($InputStringWithOffset, 'MMM dd, HH:mm z',$null)

And you actually don’t need to add a year as the current year seems to be the default.

2 Likes

Thank you @Olaf

My faulty hypothesis was that the missing year was the issue, I had not even considered the PST time zone reference might have been the problem. :face_with_open_eyes_and_hand_over_mouth:

Your help is very much appreciated.

Cheers,
Pin

Well … sometimes we can’t see the forest for the trees. :wink: :man_shrugging:t4:

1 Like