PowerShell Script: Convert To Local Time From UTC

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

13 comments

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

  5. also works

    Function Get-LocalTime($UTCTime)
    {
    $LocalTime = [System.TimeZoneInfo]::ConvertTimeFromUtc($UTCTime, [System.TimeZoneInfo]::Local)
    Return $LocalTime
    }
    
  6. Hi guys,
    I need your help how i can create sql query or reporting to checking about the using sccm 2007. Really need help on this.
    Thank you.

  7. ConvertTimeFromUtc doesn’t work if the supplied DateTime doesn’t have the “Kind” property set.

    1. Forgot to add:

      $AnyGivenUTCTimeInput = [System.DateTime]::SpecifyKind($AnyGivenUTCTimeInput, [System.DateTimeKind]::Utc)

Leave a Reply

%d bloggers like this: