代码之家  ›  专栏  ›  技术社区  ›  ashleedawg

检索本地计算机从UTC时间偏移的当前小时数(使用vba)

  •  2
  • ashleedawg  · 技术社区  · 6 年前

    人们在多个时区使用我的项目。

    最快的检索方法是什么? 本地计算机从UTC偏移的当前小时数 使用vba转换时间戳?

    1 回复  |  直到 6 年前
        1
  •  2
  •   ashleedawg    6 年前

    Option Explicit
    
    Function hoursOffsetFromUTC() As Single
        'returns current #hours difference between UTC & Local System Time
        'On Error GoTo uError
        Dim xmlHTTP As Object, strUTC As String, dtUTC As Date
        Set xmlHTTP = CreateObject("MSXML2.XMLHTTP")
        xmlHTTP.Open "GET", "https://maps.googleapis.com/maps/api/" & _
            "timezone/json?location=" & Int(Rnd() * 99) & ",0&timestamp=" & Int(Rnd() * 99), False
        xmlHTTP.send 'send randomized reqeust to avoid cached results
        strUTC = Mid(xmlHTTP.getResponseHeader("date"), 6, 20)
        Set xmlHTTP = Nothing
        dtUTC = DateValue(strUTC) + TimeValue(strUTC)
        hoursOffsetFromUTC = Round((Now() - dtUTC) * 48, 0) / 2 'nearest 0.5
        Exit Function
    uError:
        MsgBox "Couldn't get UTC time." & vbLf & vbLf & _
            "Err#" & Err & ": " & Err.Description, vbExclamation, "Error!"
    End Function
    
    • MsgBox hoursOffsetFromUTC

    Private Type SYSTEMTIME
        wYear As Integer
        wMonth As Integer
        wDayOfWeek As Integer
        wDay As Integer
        wHour As Integer
        wMinute As Integer
        wSecond As Integer
        wMilliseconds As Integer
    End Type
    
    Private Type TIME_ZONE_INFORMATION
        Bias As LongPtr
        StandardName(0 To 31) As Integer
        StandardDate As SYSTEMTIME
        StandardBias As LongPtr
        DaylightName(0 To 31) As Integer
        DaylightDate As SYSTEMTIME
        DaylightBias As LongPtr
    End Type
    
    Private Declare PtrSafe Function GetTimeZoneInformation Lib "kernel32" _
        (lpTimeZoneInformation As TIME_ZONE_INFORMATION) As Long
    
    Function hoursOffsetFromUTC_Win() As Single
        Dim TZI As TIME_ZONE_INFORMATION
        If GetTimeZoneInformation(TZI) = 2 Then
            hoursOffsetFromUTC_Win = 0 - ((TZI.Bias + TZI.DaylightBias) / 60)
        Else
            hoursOffsetFromUTC_Win = 0 - (TZI.Bias / 60)
        End If
    End Function
    
    • MsgBox hoursOffsetFromUTC_Win

    kernel32