PowerShell Script: Convert To Local Time From UTC

Written by Tao Yang

I wrote this function in the script from my previous post “SCOM MP Authoring Example: Generate alerts based on entries from SQL Database (Part 2 of 2)”. It comes handy sometimes so I thought I’ll blog it separately as well.

In PowerShell Datetime object, there is a ToUniversalTime() method that converts local time to UTC time.

image

However, there isn’t a native way to convert FROM UTC To local time. So I wrote this function:

Function Get-LocalTime($UTCTime)
{
$strCurrentTimeZone = (Get-WmiObject win32_timezone).StandardName
$TZ = [System.TimeZoneInfo]::FindSystemTimeZoneById($strCurrentTimeZone)
$LocalTime = [System.TimeZoneInfo]::ConvertTimeFromUtc($UTCTime, $TZ)
Return $LocalTime
}

image

7 comments on “PowerShell Script: Convert To Local Time From UTC

  1. I was working on adding AlertHistory to your Enhanced Email script (as I’ve not found it to be implemented anywhere after searching around Google for a while) and wanted to format the timestamps into server local time instead of UTC and this script is perfect!
    Thanks again, Tao!

    ~Tyson

  2. Thanks so much! This is exactly what i need…
    SCOM task result contains UTC time and I need to convert it to local time.

    BTW, When i google something, i am always redirected to you ,LOL

  3. Or you can just use the .NET method provided
    $UTC.ToLocalTime()

    If you want another time zone that is not local to your computer, use the DateTimeOffset object.

  4. Thanks for the script. It’s very helpful.

  5. This is only working on an English OS. This is the universal method:

    $UTC = “2006-06-07T19:00:00”
    $strCurrentTimeZone = (Get-WmiObject win32_timezone).Caption
    $r = get-childitem -path “HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Time Zones”
    foreach ($i in $r) { if ($i.GetValue(“Display”) -eq $strCurrentTimeZone) { $p = $i.PSChildName; break}}
    $tz = [TimeZoneInfo]::FindSystemTimeZoneById(($p -split “\\”)[-1])
    [TimeZoneInfo]::ConvertTimeFromUtc($UTC, $tz).ToUniversalTime()

  6. Pingback: Convert list of UTC to Current TimeZone | DL-UAT

  7. $Date = Get-Date
    $UTC = $Date.ToUniversalTime()
    $OffSet = $Date – $UTC
    $UTC.AddTicks($OffSet.Ticks)

Leave a Reply