Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display current time with time zone in PowerShell

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.

like image 683
Ken J Avatar asked Jun 14 '12 15:06

Ken J


People also ask

How do I get the current DateTime in PowerShell?

The Get-Date cmdlet gets a DateTime object that represents the current date or a date that you specify. Get-Date can format the date and time in several . NET and UNIX formats. You can use Get-Date to generate a date or time character string, and then send the string to other cmdlets or programs.

How do I compare time in PowerShell?

Comparing Dates PowerShell knows when a date is “less than” (earlier than) or “greater than” (later than) another date. To compare dates, simply create two DateTime objects using PowerShell Get Date command or perhaps by casting strings with [DateTime] and then using standard PowerShell operators like lt or gt .

How does piping work in PowerShell?

A pipeline is a series of commands connected by pipeline operators ( | ) (ASCII 124). Each pipeline operator sends the results of the preceding command to the next command. The output of the first command can be sent for processing as input to the second command. And that output can be sent to yet another command.


1 Answers

This is a better answer:

$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()

Output: 3/20/2017 11:55:55 PM

like image 75
Gavin Stevens Avatar answered Oct 17 '22 17:10

Gavin Stevens