02 October 2013

UTC using WMI

I wanted to get the current time in UTC (i.e. time without any offset) but there doesn't seem to be a timezone-style function in VBA / VBScript. Here's a function using WMI (Windows Management Instrumentation) to get time in UTC and a hack to pad the numbers so that they always have two digits. The output has this format: yyyy/mm/dd hh:mm:ss

'VBA References
'1. Microsoft WMI Scripting 1.2 Library

Function Utc() As String
  Dim ws As WbemScripting.SWbemServices, colItem As WbemScripting.SWbemObjectSet, objItem As WbemScripting.SWbemObject

  Set ws = GetObject("winmgmts:\\localhost\root\CIMV2")
  Set colItem = ws.ExecQuery("SELECT * FROM Win32_UTCTime")
  For Each objItem In colItem
    Utc = objItem.Year & "/" & Right("00" & objItem.Month, 2) & "/" & Right("00" & objItem.Day, 2) _
      & " " & Right("00" & objItem.Hour, 2) & ":" & Right("00" & objItem.Minute, 2) & ":" & Right("00" & objItem.Second, 2)
  Next

End Function