excel - 检索当前本地计算机相对于 UTC 时间的小时数(使用 VBA)

标签 excel vba ms-access timezone timezone-offset

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

为了转换时间戳,使用 VBA 仅检索本地计算机相对于 UTC 的当前小时数的最快方法是什么?

最佳答案

这里有两种现成的方法来检索当前相对于 UTC 时间的小时数,仅此而已:

方法一:使用“任何”API

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

方法二:使用Windows API

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

方法一代码较少,但需要互联网连接。它使用随机数调用 Google API 以避免缓存,并忽略响应正文,它获取响应 header 中返回的请求日期并将其与本地系统时间进行比较。 (可以使用任何在 header 中返回当前 UTC/GMT 的 API。)

方法二需要声明两种类型和一个外部函数,但无需互联网连接即可运行,使用 Windows 内部 kernel32 API 的功能。


转换时间戳:

  • 要将数字 Unix/纪元时间戳转换为“Excel Time ”:

    ( 时间戳/86400 ) + 25569 = ExcelTime

  • 或者相反,从 Excel 到纪元时间戳:

    ( ExcelTime - 25569 ) * 86400 = 时间戳

(这些不包括时区调整,因此您可以根据需要添加/减去它。)


更多信息:

关于excel - 检索当前本地计算机相对于 UTC 时间的小时数(使用 VBA),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50772101/

相关文章:

c# - 如何在 C# 中使用 oledb 仅上传 Excel 电子表格的非空行?

vba - 匹配整个单词/短语并替换

ms-access - 在 MS Access 中提供形式帮助

java - 我在 java 上遇到 SQL 语法错误,但没有任何错误

ms-access - 在 VBA 数组上调用 LBound() 或 UBound() 时出现 "Subscript out of range"错误

excel - 如何从三个变量构建复值?

R中的Sqldf - 第一列名称错误

excel - 无法让我的代码执行特殊粘贴

sql - 在 SQL/VBA 中高效地填写大量字段

sql - 在表单内的Access中的三个子表单中显示基于相同ID的记录