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

4 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.

Leave a Reply