You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell:如何在UTC转本地时间输出后添加时区缩写

PowerShell UTC时间戳转本地时间并添加时区缩写

问题

现有一段PowerShell脚本可将UTC时间戳转换为本地时间,输出格式为Wednesday, March 20, 2024 12:26:00 PM,需要在输出末尾添加本地3字母时区缩写(如PST),但直接拼接字符串会破坏原有时间格式。

原脚本

#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

原输出

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

期望输出

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

用户尝试过Write-Output "$($result) $($localtzid)"、Write-Output $result, $localtzid -join ','等方法,均会改变原有时间格式。

解决方案

核心思路是先将DateTime对象格式化为与原输出完全一致的字符串,再拼接时区缩写,避免PowerShell自动转换格式。

完整修正脚本

#input format:  '2024-03-20 19:26 Z'
param ($timestamp)

# 转换UTC时间到本地时间
$localTime = [System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date -Date $timestamp), (Get-TimeZone).Id)

# 获取本地时区3字母缩写(如PST/PDT)
$localtzAbbr = -join ([System.TimeZoneInfo]::Local.Id.Split() | ForEach-Object { $_[0] })

# 保持原时间格式并拼接时区缩写
$formattedOutput = "{0} {1}" -f $localTime.ToString("F"), $localtzAbbr

Write-Output $formattedOutput

关键说明

  1. 时区缩写获取:通过拆分本地时区ID并取每个部分的首字母拼接,比如Pacific Standard Time会得到PST,夏令时期间Pacific Daylight Time会得到PDT。
  2. 时间格式化:ToString("F")是.NET的完整日期时间格式符,生成的字符串和原输出完全一致。如果需要自定义格式,可替换为对应的格式字符串,比如"dddd, MMMM dd, yyyy hh:mm:ss tt"效果相同。
  3. 字符串拼接:使用PowerShell的格式运算符-f确保格式稳定,避免直接拼接DateTime对象导致的自动格式转换。

内容的提问来源于stack exchange,提问作者LagunaJim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 15:09:54