2

I'm running into a weird issue where I'm trying to parse an array of the following strings, which have been given the variable $DatesUnformatted:

2020-02-28T05:29:00Z
2020-02-28T04:52:00Z
2020-02-28T04:52:00Z
2020-02-27T17:01:00Z
2020-02-27T17:01:00Z
2020-02-27T17:01:00Z
2020-02-27T17:01:00Z

...to a time format (hh:mm tt) using [DateTime]::ParseExact().

My script looks like something like this:

foreach ($DateUnformatted in $DatesUnformatted)
{
    $DateFormatted = [datetime]::parseexact($DateUnformatted, 'yyyy-MM-ddThh:mm:ssZ',$null).ToString('hh:mm tt')
    echo "Converting $DateUnformatted to $DateFormatted"
}

And here's the output:

Converting 2020-02-28T05:29:00Z to 12:29 AM
Converting 2020-02-28T04:52:00Z to 11:52 PM
Converting 2020-02-28T04:52:00Z to 11:52 PM
Converting 2020-02-27T17:01:00Z to 11:52 PM
Converting 2020-02-27T17:01:00Z to 11:52 PM
Converting 2020-02-27T17:01:00Z to 11:52 PM
Converting 2020-02-27T17:01:00Z to 11:52 PM

It seems like it's only converting the first few entries then just repeating one until the end of the loop. Any ideas?

Lance U. Matthews
  • 15,725
  • 6
  • 48
  • 68
bsander
  • 59
  • 1
  • 5

2 Answers2

3

hh only works for 12-hour time formats (with AM/PM designators), whereas your input uses 24-hour format, for which you must use HH:

[datetime]::ParseExact(
  $DateUnformatted, 
  'yyyy-MM-ddTHH:mm:ssZ', # note the 'HH'
  $null
).ToString('hh:mm tt')

Your symptom implies that $ErrorActionPreference = 'SilentlyContinue' was in effect, otherwise you would have seen the ParseExact() method trigger its statement-terminating errors loudly, with error messages such as:

Exception calling "ParseExact" with "3" argument(s): "String '2020-02-27T17:01:00Z' was not recognized as a valid DateTime."

Either way, the last successful call's result lingered in variable $DateFormatted.

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • 1
    Looks like my comment got deleted after submitting an edit. Yes you are correct that the $ErrorActionPreference was set to 'SilentlyContinue.' The actual script is using an API to grab events that may or may not contain a date string so I was getting a lot of errors. Not ideal when printing the stdout/stderr to an Ansible playbook run. Thanks again! – bsander Feb 29 '20 at 05:12
0

You can also just implicitly convert strings to datatime like this:

([datetime]'2020-02-28T04:52:00Z').ToString('hh:mm tt')

Full code:

$DatesUnformatted | foreach { "Converting $_ to " + ([datetime]$_).ToString('hh:mm tt') }
MikeSh
  • 352
  • 1
  • 5