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.
While this is a bit ... naive perhaps, it's one way to get an abbreviation without a switch statement:
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 betweenDateTime
andTimeZoneInfo
, 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 forStandardName
.EDIT: I did some more investigation changing the time zone on my computer manually to check this and a
TimeZoneInfo
forGMT+12
looks like this:Which produces this result for my code:
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:
I just combined several scripts and finally was able to run the script in my domain controller.
The script provides the output of time and timezone for all the machines connected under the domain. We had a major issue with our application servers and used this script to cross check the time and timezone.
Russia, France, Norway, Germany:
Output for Russian time zone: 22:47:27 Чт 21.11.19 г. +03:00
Others - just change the code.
This is a better answer:
Output: 3/20/2017 11:55:55 PM
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.This returns:
Be loath to define another datetime format! Use an existing one, such as RFC 1123. There's even a PowerShell shortcut!
Ref.: Get-Date