Display current time with time zone in PowerShell Display current time with time zone in PowerShell powershell powershell

Display current time with time zone in PowerShell


While this is a bit ... naive perhaps, it's one way to get an abbreviation without a switch statement:

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

My regular expression probably leaves something to be desired.

The output of the above for my time zone is EST. I did some looking as I wanted to see what the value would be for other GMT offset settings, but .NET doesn't seem to have very good links between DateTime and TimeZoneInfo, so I couldn't just programmatically run through them all to check. This might not work properly for some of the strings that come back for StandardName.

EDIT: I did some more investigation changing the time zone on my computer manually to check this and a TimeZoneInfo for GMT+12 looks like this:

PS> [TimeZoneInfo]::LocalId                         : UTC+12DisplayName                : (GMT+12:00) Coordinated Universal Time+12StandardName               : UTC+12DaylightName               : UTC+12BaseUtcOffset              : 12:00:00SupportsDaylightSavingTime : False

Which produces this result for my code:

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

So, I guess you'd have to detect whether the StandardName appears to be a set of words or just offset designation because there's no standard name for it.

The less problematic ones outside the US appear to follow the three-word format:

PS> [TimeZoneInfo]::LocalId                         : Tokyo Standard TimeDisplayName                : (GMT+09:00) Osaka, Sapporo, TokyoStandardName               : Tokyo Standard TimeDaylightName               : Tokyo Daylight TimeBaseUtcOffset              : 09:00:00SupportsDaylightSavingTime : FalsePS> [Regex]::Replace([System.TimeZoneInfo]::Local.StandardName, '([A-Z])\w+\s*', '$1')TST


You should look into DateTime format strings. Although I'm not sure they can return a time zone short name, you can easily get an offset from UTC.

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

This returns:

8:00:34 AM -04:00


Be loath to define another datetime format! Use an existing one, such as RFC 1123. There's even a PowerShell shortcut!

Get-Date -format r

Thu, 14 Jun 2012 16:44:18 GMT

Ref.: Get-Date