14

我正在尝试使用 TimeZone 在我的系统上显示本地时间。如何在任何系统上以这种最简单的方式显示时间?:

时间:美国东部标准时间上午 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

我希望能够在不依赖简单逻辑的情况下显示时间,但能够在任何系统上提供本地时区。

4

7 回答 7

12

虽然这有点......也许很天真,但这是在没有 switch 语句的情况下获得缩写的一种方法

[Regex]::Replace([System.TimeZoneInfo]::Local.StandardName, '([A-Z])\w+\s*', '$1')

我的正则表达式可能还有一些不足之处。

我的时区的上述输出是EST. 我做了一些查看,因为我想看看其他 GMT 偏移设置的值是多少,但是 .NET 似乎在DateTime和之间没有很好的链接TimeZoneInfo,所以我不能只是以编程方式运行它们来检查。对于某些返回的字符串,这可能无法正常工作StandardName

编辑:我做了更多调查,手动更改计算机上的时区以检查这一点,TimeZoneInfoforGMT+12看起来像这样:

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
于 2012-06-14T19:48:46.467 回答
8

您应该查看DateTime格式字符串。虽然我不确定他们是否可以返回时区短名称,但您可以轻松获得与 UTC 的偏移量。

$formatteddate = "{0:h:mm:ss tt zzz}" -f (get-date)

这将返回:

8:00:34 AM -04:00
于 2012-06-14T15:34:52.563 回答
5

不愿定义另一种日期时间格式!使用现有的,例如RFC 1123。甚至还有一个 PowerShell 快捷方式!

Get-Date -format r

格林威治标准时间 2012 年 6 月 14 日星期四 16:44:18

参考:获取日期

于 2012-06-14T15:45:32.463 回答
2

这是一个更好的答案:

$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 日晚上 11:55:55

于 2017-03-21T04:46:17.883 回答
1

我不知道有任何对象可以为您完成这项工作。您可以将逻辑包装在一个函数中:

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)
于 2012-06-14T15:26:05.220 回答
0

我只是结合了几个脚本,最后能够在我的域控制器中运行脚本。

该脚本为域下连接的所有机器提供时间和时区的输出。我们的应用程序服务器出现了一个重大问题,并使用此脚本来交叉检查时间和时区。

# 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
于 2016-07-08T12:17:45.787 回答
0

俄罗斯、法国、挪威、德国:

get-date -format "HH:mm:ss ddd dd'.'MM'.'yy' г.' zzz"

俄罗斯时区的输出:22:47:27 Чт 21.11.19 г。+03:00

其他 - 只需更改代码。

于 2019-11-21T19:45:42.680 回答