3

PowerShell Script: Convert To Local Time From UTC

Posted by Tao Yang on 11/01/2012 in PowerShell |

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

Tags:

3 Comments

  • Tyson says:

    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

  • Samuel says:

    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

  • karimahta says:

    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.

Leave a Reply

Copyright © 2010-2014 Tao Yang's System Management Blog All rights reserved.
This site is using the Desk Mess Mirrored theme, v2.2.4.1, from BuyNowShop.com.