人们在多个时区使用我的项目。
为了转换时间戳,最简单的方法是使用VBA检索本地计算机与UTC 的当前小时数,以便转换时间戳?
答案 0 :(得分:2)
这里有两种现成的方法可以检索当前的UTC时间偏移小时数,仅此而已:
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×tamp=" & 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
方法一代码较少但需要互联网连接。它使用随机数调用Google API以避免缓存,并忽略响应正文,它会抓取响应标头中返回的请求日期,并将其与本地系统时间进行比较。 (可以使用任何在标头中返回当前UTC / GMT的API。)
方法二需要使用Windows内部kernel32
API的功能声明两种类型和外部函数,但在没有互联网连接的情况下运行。
将数字Unix /纪元时间戳转换为“Excel Time”:
(时间戳/ 86400)+ 25569 = ExcelTime
或者相反,从Excel到纪元时间戳:
(ExcelTime - 25569)* 86400 =时间戳
(这些不包括时区调整,因此您可以根据需要添加/减去它。)
维基百科:Unix Time& Digital Timestamps
EpochConverter:Epoch & Unix Timestamp Conversion Tools
Chip Pearson:Time Zones And Daylight Savings Time(Windows API)
堆栈溢出:Convert between arbitrary timezones(区域→区域)
Microsoft支持:How to use times and dates in Excel