我正在尝试使用时区在我的系统上显示本地时间。如何在任何系统上以最简单的方式以这种格式显示时间?
时间:美国东部时间上午 8:00:34
我目前正在使用以下脚本:
$localtz = [System.TimeZoneInfo]::Local | Select-Object -expandproperty Id
if ($localtz -match "Eastern") {$x = " EST"}
if ($localtz -match "Pacific") {$x = " PST"}
if ($localtz -match "Central") {$x = " CST"}
"Time: " + (Get-Date).Hour + ":" + (Get-Date).Minute + ":" + (Get-Date).Second + $x
我希望能够在不依赖简单逻辑的情况下显示时间,但能够在任何系统上给出本地时区。
这有点...也许很天真,这是在没有 switch 语句的情况下获取缩写的一种方法:
[Regex]::Replace([System.TimeZoneInfo]::Local.StandardName, '([A-Z])w+s*', '$1')
我的正则表达式可能还有一些不足之处。
对于我的时区,上述输出是 EST
.我做了一些查看,因为我想看看其他 GMT 偏移量设置的值是多少,但 .NET 似乎在DateTime
和TimeZoneInfo
之间没有很好的链接,所以我不能只是以编程方式运行它们来检查。对于某些返回StandardName
的字符串,这可能无法正常工作。
编辑:我做了更多的调查,手动更改计算机上的时区以检查这一点,GMT+12
的TimeZoneInfo
如下所示:
PS> [TimeZoneInfo]::Local
Id : UTC+12
DisplayName : (GMT+12:00) Coordinated Universal Time+12
StandardName : UTC+12
DaylightName : UTC+12
BaseUtcOffset : 12:00:00
SupportsDaylightSavingTime : False
这为我的代码生成了以下结果:
PS> [Regex]::Replace([System.TimeZoneInfo]::Local.StandardName, '([A-Z])w+s*', '$1')
U+12
所以,我想你必须检测StandardName
似乎是一组单词还是只是偏移名称,因为它没有标准名称。
美国以外的问题较少的人似乎遵循三个单词的格式:
PS> [TimeZoneInfo]::Local
Id : Tokyo Standard Time
DisplayName : (GMT+09:00) Osaka, Sapporo, Tokyo
StandardName : Tokyo Standard Time
DaylightName : Tokyo Daylight Time
BaseUtcOffset : 09:00:00
SupportsDaylightSavingTime : False
PS> [Regex]::Replace([System.TimeZoneInfo]::Local.StandardName, '([A-Z])w+s*', '$1')
TST
您应该研究DateTime
格式字符串。虽然我不确定他们是否可以返回时区短名称,但您可以轻松地获得 UTC 的偏移量。
$formatteddate = "{0:h:mm:ss tt zzz}" -f (get-date)
这将返回:
8:00:34 AM -04:00
不愿意定义另一种日期时间格式!使用现有的,例如 RFC 1123。甚至还有一个PowerShell快捷方式!
Get-Date -format r
周四, 14 六月 2012 16:44:18 GMT
参考: 获取日期
这是一个更好的答案:
$A = Get-Date #Returns local date/time
$B = $A.ToUniversalTime() #Convert it to UTC
# Figure out your current offset from UTC
$Offset = [TimeZoneInfo]::Local | Select BaseUtcOffset
#Add the Offset
$C = $B + $Offset.BaseUtcOffset
$C.ToString()
输出:2017/3/20 23:55:55
有任何对象可以为您完成工作。您可以将逻辑包装在一个函数中:
function Get-MyDate{
$tz = switch -regex ([System.TimeZoneInfo]::Local.Id){
Eastern {'EST'; break}
Pacific {'PST'; break}
Central {'CST'; break}
}
"Time: {0:T} $tz" -f (Get-Date)
}
Get-MyDate
或者甚至取时区 id 的首字母:
$tz = -join ([System.TimeZoneInfo]::Local.Id.Split() | Foreach-Object {$_[0]})
"Time: {0:T} $tz" -f (Get-Date)
我只是组合了几个脚本,终于能够在域控制器中运行该脚本。
该脚本为域下连接的所有计算机提供时间和时区的输出。我们的应用程序服务器遇到了一个主要问题,并使用此脚本交叉检查时间和时区。
# The below scripts provides the time and time zone for the connected machines in a domain
# Appends the output to a text file with the time stamp
# Checks if the host is reachable or not via a ping command
Start-Transcript -path C:output.txt -append
$ldapSearcher = New-Object directoryservices.directorysearcher;
$ldapSearcher.filter = "(objectclass=computer)";
$computers = $ldapSearcher.findall();
foreach ($computer in $computers)
{
$compname = $computer.properties["name"]
$ping = gwmi win32_pingstatus -f "Address = '$compname'"
$compname
if ($ping.statuscode -eq 0)
{
try
{
$ErrorActionPreference = "Stop"
Write-Host “Attempting to determine timezone information for $compname…”
$Timezone = Get-WMIObject -class Win32_TimeZone -ComputerName $compname
$remoteOSInfo = gwmi win32_OperatingSystem -computername $compname
[datetime]$remoteDateTime = $remoteOSInfo.convertToDatetime($remoteOSInfo.LocalDateTime)
if ($Timezone)
{
foreach ($item in $Timezone)
{
$TZDescription = $Timezone.Description
$TZDaylightTime = $Timezone.DaylightName
$TZStandardTime = $Timezone.StandardName
$TZStandardTime = $Timezone.StandardTime
}
Write-Host "Timezone is set to $TZDescription`nTime and Date is $remoteDateTime`n**********************`n"
}
else
{
Write-Host ("Something went wrong")
}
}
catch
{
Write-Host ("You have insufficient rights to query the computer or the RPC server is not available.")
}
finally
{
$ErrorActionPreference = "Continue"
}
}
else
{
Write-Host ("Host $compname is not reachable from ping `n")
}
}
Stop-Transcript
俄罗斯、法国、挪威、德国:
get-date -format "HH:mm:ss ddd dd'.'MM'.'yy' г.' zzz"
俄罗斯时区输出: 22:47:27 Чт 21.11.19 г. +03:00
其他 - 只需更改代码。
如果您有互联网连接...应用程序接口
Function tzAbbreviation {
Try {
$webData = Invoke-WebRequest -Uri "https://worldtimeapi.org/api/ip" -UseBasicParsing -TimeoutSec 3 -ErrorAction Stop
$Content = ConvertFrom-Json $webData.Content
Return $($Content.Abbreviation)
}
Catch {}
}
$tzAbbreviation = tzAbbreviation
在荷兰...
输出:欧洲中部时间
减去脚本看到的内容
有时,TimeZoneInfo Local 与脚本查找的内容不同。例如,我注意到我的偏离了一个小时,其中报告了 -5,但 PS 脚本(获取日期)是 -4。在可能的情况下,也使用 [datetime]::UtcNow 而不是 get-date。
解释:
而不是依赖本地时间"[时区信息]::本地 |选择BaseUtcOffset',找出两个日期之间的脚本差异
((Get-Date).ToUniversalTime() - (Get-Date)).TotalHours
- 注意:这假设 UTC 以西,否则反转数学或更改为 +。
这是一组有趣的答案,因为很大程度上取决于您希望如何查看时区的缩写形式。 有些带有数字偏移量,有些只是文本。 这是我对字母数字时区缩写的解决方案,处理夏令时,以及处理没有"标准名称"的情况。 我已经测试了美国版 Windows 10 中可用的时区,虽然它们并不都是唯一或准确的,但它可以满足我的需求。 我将不胜感激任何反馈:
function Get-TimeZoneAbbreviation {
[CmdletBinding()] param ([TimeZoneInfo]$timeZoneInfo = [TimeZoneInfo]::Local, $daylightSavingsTime = $null)
$result = ""
# If DST parameter is left empty, calculate DST from current time in that time zone.
if ($daylightSavingsTime -eq $null) {
$daylightSavingsTime = $timeZoneInfo.IsDaylightSavingTime([TimeZoneInfo]::ConvertTimeFromUtc([DateTime]::UtcNow, $timeZoneInfo))
}
# If DST is supplied as true, but isn't supported return null.
elseif ($daylightSavingsTime -and !$timeZoneInfo.SupportsDaylightSavingTime) {
return $null
}
# Get standard or daylight name.
$tzFullName = $timeZoneInfo.StandardName
if ($daylightSavingsTime) {
$tzFullName = $timeZoneInfo.DaylightName
}
# If name doesn't have multiple words then just return the name.
$tzSplit = $tzFullName.Split(" ")
if ($tzSplit.Length -eq 1) {
return $tzFullName
}
# Return abbreviation as first character of each word.
foreach ($tzC in $tzSplit) {
$result += [regex]::Replace($tzC, "[^a-zA-Z0-9 -]", "").Substring(0, 1)
}
return $result
}
用法(我只指定字符串,所以我可以使用 PadRight 进行输出):
# Output for original question:
[string]$tzaLocalNow = @(Get-TimeZoneAbbreviation)
"Local Time Now: " + @(Get-Date -Format "HH:mm:ss ") + $tzaLocalNow
# Output using DST parameter
[string]$tzaLocalStandard = @(Get-TimeZoneAbbreviation -daylightSavingsTime $false)
[string]$tzaLocalDaylight = @(Get-TimeZoneAbbreviation -daylightSavingsTime $true)
Write-Host @("`n" + $tzaLocalNow.PadRight(10) + $tzaLocalStandard.PadRight(10) + $tzaLocalDaylight + "`n")
# Output table of all system time zone abbreviations.
foreach ($tz in (Get-TimeZone -ListAvailable)) {
[string]$tzaNow = @(Get-TimeZoneAbbreviation $tz)
[string]$tzaStandard = @(Get-TimeZoneAbbreviation $tz $false)
[string]$tzaDaylight = @(Get-TimeZoneAbbreviation $tz $true)
Write-Host @($tzaNow.PadRight(10) + $tzaStandard.PadRight(10) + $tzaDaylight)
}
为了使您不必自己运行它,下表在最右侧的列中显示了结果:
DisplayName Offset St Ds
==================================================================================
(UTC-12:00) International Date Line West -12 DST
(UTC-11:00) Coordinated Universal Time-11 -11 UTC-11
(UTC-10:00) Aleutian Islands -10 AST ADT
(UTC-10:00) Hawaii -10 HST
(UTC-09:30) Marquesas Islands -09 MST
(UTC-09:00) Alaska -09 AST ADT
(UTC-09:00) Coordinated Universal Time-09 -09 UTC-09
(UTC-08:00) Baja California -08 PSTM PDTM
(UTC-08:00) Coordinated Universal Time-08 -08 UTC-08
(UTC-08:00) Pacific Time (US & Canada) -08 PST PDT
(UTC-07:00) Arizona -07 UMST
(UTC-07:00) La Paz, Mazatlan -07 MSTM MDTM
(UTC-07:00) Mountain Time (US & Canada) -07 MST MDT
(UTC-07:00) Yukon -07 YST YDT
(UTC-06:00) Central America -06 CAST
(UTC-06:00) Central Time (US & Canada) -06 CST CDT
(UTC-06:00) Easter Island -06 EIST EIDT
(UTC-06:00) Guadalajara, Mexico City, Monterrey -06 CSTM CDTM
(UTC-06:00) Saskatchewan -06 CCST
(UTC-05:00) Bogota, Lima, Quito, Rio Branco -05 SPST
(UTC-05:00) Chetumal -05 ESTM EDTM
(UTC-05:00) Eastern Time (US & Canada) -05 EST EDT
(UTC-05:00) Haiti -05 HST HDT
(UTC-05:00) Havana -05 CST CDT
(UTC-05:00) Indiana (East) -05 UEST UEDT
(UTC-05:00) Turks and Caicos -05 TaCST TaCDT
(UTC-04:00) Asuncion -04 PST PDT
(UTC-04:00) Atlantic Time (Canada) -04 AST ADT
(UTC-04:00) Caracas -04 VST VDT
(UTC-04:00) Cuiaba -04 CBST CBDT
(UTC-04:00) Georgetown, La Paz, Manaus, San Juan -04 SWST
(UTC-04:00) Santiago -04 PSST PSDT
(UTC-03:30) Newfoundland -03 NST NDT
(UTC-03:00) Araguaina -03 TST TDT
(UTC-03:00) Brasilia -03 ESAST ESADT
(UTC-03:00) Cayenne, Fortaleza -03 SEST
(UTC-03:00) City of Buenos Aires -03 AST ADT
(UTC-03:00) Greenland -03 GST GDT
(UTC-03:00) Montevideo -03 MST MDT
(UTC-03:00) Punta Arenas -03 MST MDT
(UTC-03:00) Saint Pierre and Miquelon -03 SPST SPDT
(UTC-03:00) Salvador -03 BST BDT
(UTC-02:00) Coordinated Universal Time-02 -02 UTC-02
(UTC-02:00) Mid-Atlantic - Old -02 MST MDT
(UTC-01:00) Azores -01 AST ADT
(UTC-01:00) Cabo Verde Is. -01 CVST
(UTC) Coordinated Universal Time 00 CUT
(UTC+00:00) Dublin, Edinburgh, Lisbon, London 00 GST GDT
(UTC+00:00) Monrovia, Reykjavik 00 GST
(UTC+00:00) Sao Tome 00 STST STDT
(UTC+01:00) Casablanca 00 MST MDT
(UTC+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna +01 WEST WEDT
(UTC+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague +01 CEST CEDT
(UTC+01:00) Brussels, Copenhagen, Madrid, Paris +01 RST RDT
(UTC+01:00) Sarajevo, Skopje, Warsaw, Zagreb +01 CEST CEDT
(UTC+01:00) West Central Africa +01 WCAST
(UTC+02:00) Athens, Bucharest +02 GST GDT
(UTC+02:00) Beirut +02 MEST MEDT
(UTC+02:00) Cairo +02 EST EDT
(UTC+02:00) Chisinau +02 EEST EEDT
(UTC+02:00) Damascus +02 SST SDT
(UTC+02:00) Gaza, Hebron +02 WBGST WBGDT
(UTC+02:00) Harare, Pretoria +02 SAST
(UTC+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius +02 FST FDT
(UTC+02:00) Jerusalem +02 JST JDT
(UTC+02:00) Juba +02 SSST SSDT
(UTC+02:00) Kaliningrad +02 RT1ST RT1DT
(UTC+02:00) Khartoum +02 SST SDT
(UTC+02:00) Tripoli +02 LST LDT
(UTC+02:00) Windhoek +02 NST NDT
(UTC+03:00) Amman +03 JST JDT
(UTC+03:00) Baghdad +03 AST ADT
(UTC+03:00) Istanbul +03 TST TDT
(UTC+03:00) Kuwait, Riyadh +03 AST
(UTC+03:00) Minsk +03 BST BDT
(UTC+03:00) Moscow, St. Petersburg +03 RT2ST RT2DT
(UTC+03:00) Nairobi +03 EAST
(UTC+03:00) Volgograd +03 VST VDT
(UTC+03:30) Tehran +03 IST IDT
(UTC+04:00) Abu Dhabi, Muscat +04 AST
(UTC+04:00) Astrakhan, Ulyanovsk +04 AST ADT
(UTC+04:00) Baku +04 AST ADT
(UTC+04:00) Izhevsk, Samara +04 RT3ST RT3DT
(UTC+04:00) Port Louis +04 MST MDT
(UTC+04:00) Saratov +04 SST SDT
(UTC+04:00) Tbilisi +04 GST
(UTC+04:00) Yerevan +04 CST CDT
(UTC+04:30) Kabul +04 AST
(UTC+05:00) Ashgabat, Tashkent +05 WAST
(UTC+05:00) Ekaterinburg +05 RT4ST RT4DT
(UTC+05:00) Islamabad, Karachi +05 PST PDT
(UTC+05:00) Qyzylorda +05 QST QDT
(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi +05 IST
(UTC+05:30) Sri Jayawardenepura +05 SLST
(UTC+05:45) Kathmandu +05 NST
(UTC+06:00) Astana +06 CAST
(UTC+06:00) Dhaka +06 BST BDT
(UTC+06:00) Omsk +06 OST ODT
(UTC+06:30) Yangon (Rangoon) +06 MST
(UTC+07:00) Bangkok, Hanoi, Jakarta +07 SAST
(UTC+07:00) Barnaul, Gorno-Altaysk +07 AST ADT
(UTC+07:00) Hovd +07 WMST WMDT
(UTC+07:00) Krasnoyarsk +07 RT6ST RT6DT
(UTC+07:00) Novosibirsk +07 NST NDT
(UTC+07:00) Tomsk +07 TST TDT
(UTC+08:00) Beijing, Chongqing, Hong Kong, Urumqi +08 CST
(UTC+08:00) Irkutsk +08 RT7ST RT7DT
(UTC+08:00) Kuala Lumpur, Singapore +08 MPST
(UTC+08:00) Perth +08 WAST WADT
(UTC+08:00) Taipei +08 TST
(UTC+08:00) Ulaanbaatar +08 UST UDT
(UTC+08:45) Eucla +08 ACWST
(UTC+09:00) Chita +09 TST TDT
(UTC+09:00) Osaka, Sapporo, Tokyo +09 TST
(UTC+09:00) Pyongyang +09 NKST NKDT
(UTC+09:00) Seoul +09 KST
(UTC+09:00) Yakutsk +09 RT8ST RT8DT
(UTC+09:30) Adelaide +09 CAST CADT
(UTC+09:30) Darwin +09 ACST
(UTC+10:00) Brisbane +10 EAST
(UTC+10:00) Canberra, Melbourne, Sydney +10 AEST AEDT
(UTC+10:00) Guam, Port Moresby +10 WPST
(UTC+10:00) Hobart +10 TST TDT
(UTC+10:00) Vladivostok +10 RT9ST RT9DT
(UTC+10:30) Lord Howe Island +10 LHST LHDT
(UTC+11:00) Bougainville Island +11 BST BDT
(UTC+11:00) Chokurdakh +11 RT1ST RT1DT
(UTC+11:00) Magadan +11 MST MDT
(UTC+11:00) Norfolk Island +11 NST NDT
(UTC+11:00) Sakhalin +11 SST SDT
(UTC+11:00) Solomon Is., New Caledonia +11 CPST
(UTC+12:00) Anadyr, Petropavlovsk-Kamchatsky +12 RT1ST RT1DT
(UTC+12:00) Auckland, Wellington +12 NZST NZDT
(UTC+12:00) Coordinated Universal Time+12 +12 UTC+12
(UTC+12:00) Fiji +12 FST FDT
(UTC+12:00) Petropavlovsk-Kamchatsky - Old +12 KST KDT
(UTC+12:45) Chatham Islands +12 CIST CIDT
(UTC+13:00) Coordinated Universal Time+13 +13 UTC+13
(UTC+13:00) Nuku'alofa +13 TST TDT
(UTC+13:00) Samoa +13 SST SDT
(UTC+14:00) Kiritimati Island +14 LIST