Display current time with time zone in PowerShell

2020-06-12 02:41发布

I'm trying to display the local time on my system with the TimeZone. How can I display time in this format the simplest way possible on any system?:

Time: 8:00:34 AM EST

I'm currently using the following script:

$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

I'd like to be able to display the time without relying on simple logic, but be able to give the local timezone on any system.

7条回答
forever°为你锁心
2楼-- · 2020-06-12 03:35

I'm not aware of any object that can do the work for you. You could wrap the logic in a function:

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

Or even take the initials of the time zone id:

$tz = -join ([System.TimeZoneInfo]::Local.Id.Split() | Foreach-Object {$_[0]})
"Time: {0:T} $tz" -f (Get-Date)
查看更多
登录 后发表回答