Wednesday, November 21, 2012

Converting UTC to Local time using VBScript

Hi all.

I've recently searched for a possibility to convert UTC times to local times using VBScript. Every solution I found dealt with string parsing the UTC time value by splitting it into pieces and then adding the timezone bias, retrieved from the registry. That's a crude method, and it is NOT neccessary...

The SWbemDateTime object provides properties and methods to do this conversion directly:

Function ConvertUTCToLocal( varTime )
    Dim myObj, MyDate
    MyDate = CDate( varTime )
    Set myObj = CreateObject( "WbemScripting.SWbemDateTime" )
    myObj.Year = Year( MyDate )
    myObj.Month = Month( MyDate )
    myObj.Day = Day( MyDate )
    myObj.Hours = Hour( MyDate )
    myObj.Minutes = Minute( myDate )
    myObj.Seconds = Second( myDate )
    ConvertUTCToLocal = myObj.GetVarDate( True )
End Function

As long as you do not set the .UTC property, the properties you set are UTC time, and GetVarDate returns the local time. And, of course, you can do this the other way - using .SetVarDate and then retrieving the various properties of the DateTime object. In this scenario, of course, you have to retrieve the .UTC property and add it accordingly...

The SWbemDateTimeObject:

regards, Martin


  1. Just what I needed. I was struggling doing this the "hard" way, then stumbled upon your post via Google.

    Thanks much!

  2. Awesome. Thanks for this. So much better than parsing and calculating.

  3. Amazing, this is so much better than the other crazy solutions I was finding. This makes it as easy as in .Net!

  4. It worked like a charm, thanks!