Outputting two variables on a single line without changes to the variables

66 Views Asked by At

Inexperienced with PowerShell, here's a snippet that takes a timestamp in UTC (Zulu) and converts it to local time.

#input format:  '2024-03-20 19:26 Z'
param ($timestamp)
$result = [System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date -Date $timestamp), (Get-TimeZone | Select-Object -ExpandProperty Id))
Write-Output $result

This gets me the output:

Wednesday, March 20, 2024 12:26:00 PM

Now I want to add on the end of this output the local 3-letter time zone abbreviation (e.g. PST)

I found this command and it gets me close:

$localtzid = -join ([System.TimeZoneInfo]::Local.Id.Split() | Foreach-Object {$_[0]})
"Time: {0:T} $tz" -f (Get-Date)

..gets me the time on one line and then the 3-letter abbreviation on the next line.

What I want to achieve is this:

Wednesday, March 20, 2024 12:26:00 PM PST

I've tried Write-Output "$($result) $($localtzid)" - changes the format entirely. I've tried Write-Output $result, $localtzid -join ',' - changes the format entirely. I tried concat... I tried so many things.

1

There are 1 best solutions below

1
mklement0 On BEST ANSWER

Given that time-zone names, including initialisms such as PST, aren't universally standardized, I suggest formatting your date with a UTC offset, (e.g. -07:00) instead:

& {
  param ([string] $timestamp)
  $localTime = [datetime] $timestamp
  $localTime.ToString('F') + ' ' + $localTime.ToString('zzz')
} '2024-03-20 19:26 Z'

E.g., in the US Pacific time zone the output is:
Wednesday, March 20, 2024 12:26:00 PM -07:00


If you still want to use an initialism such as PST and derive it from the initial letters of the full name of the local time zone, more work is needed:

& {
  param ($timestamp)
  $time = [datetimeoffset] [datetime] $timestamp
  $localTimeZone = [System.TimeZoneInfo]::Local
  $isDstTime = $time.Offset -ne $localTimeZone.BaseUtcOffset
  $timeZoneName = ($localTimeZone.StandardName, $localTimeZone.DaylightName)[$isDstTime]
  $time.ToString('F') + ' ' + (-join (-split $timeZoneName).ForEach({ $_[0] }))
} '2024-03-20 19:26 Z'

This should result in Wednesday, March 20, 2024 12:26:00 PM PDT in the US Pacific time zone.
Note that PDT (from Pacific Daylight Time rather than PST (from Pacific Standard Time) is used, because the timestamp falls into the daylight-saving period.