在任意时区之间转换

Convert between arbitrary timezones

我正在尝试寻找一种简单而可靠的方法来转换任意时区之间的时间。

这:http://www.cpearson.com/excel/TimeZoneAndDaylightTime.aspx 仅说明如何在我的(当前)TZ 和另一个 TZ 之间进行转换。

那两篇 SO 文章 (Getting Windows Time Zone Information (C++/MFC) and How do you get info for an arbitrary time zone in Windows?) 讨论了从注册表中获取信息。

这听起来有点太费时费力了;此外,Windows 似乎将 TZ 存储在它们的 "full names" 中(例如 (UTC-08:00) Pacific Time (US & Canada)),我宁愿使用缩写(例如 EDT)来引用 TZ。此外,依赖 Windows 注册表也可能是不安全的:不同的用户可能有不同的版本,有些可能不是最新的。这意味着两个人的报告 运行 可能会提供两个不同的结果!

是否有更简单且更健壮的方法?编写查询 table 可能会工作一段时间,但当政府决定废除 DST 或更改任何其他内容时,它就会被破坏。

也许可以从 Internet 上获取 TZ 列表并进行解析?这样够安全吗?

更新 1

我已经进行了研究并探索了各种可能性,但这个问题并不像看起来那么微不足道。如果您认为函数应该类似于 bTime = aTime + 3,那么请重新考虑。时区和 DST 处于不断变化的状态。

阅读此内容以供参考:list of pending / proposed timezone changes。请注意,一些国家/地区实际上正在更改其 时区 ,而不仅仅是 DST 设置!巴西将他们更改时钟的日期更改为冬季时间!所有这些更改会很快破坏静态查找 table。

更新 2

我不是在研究一个快速而肮脏的 hack,我可以自己想出这个。我不想写一些东西然后忘记它;我想创建一个函数,它可以被其他人安全地用于不同的内部项目,而无需维护噩梦。 已知 偶尔更改的硬编码常量是非常糟糕的软件设计(想想由一段非常非常古老的代码引起的 Y2K 错误)。

更新 3

这个数据库看起来不错(虽然我不确定它是否足够table):https://timezonedb.com/api。他们甚至有一个 TZ 转换电话 - 正是我需要的!我可能会尝试从 VBA 解析 XML 并分享我的结果。

恐怕与时区有关的任何事情都不是一件容易的事(问任何网页设计师,他们都会说这是一个巨大的挑战)

有两种方法可以解决您的问题

1) 简单方法 - 创建一个中央列表,所有其他工作簿都链接到该列表。这可以保存在 SharePoint 或共享驱动器上,然后您只需更新这个 table

2) 困难的方法 - 使用网站 API 获取最新的时区数据。 https://www.amdoren.com/ 是一个不错的站点,您可以通过注册获得免费的 API 密钥。唯一的问题是您必须从网站解析 Json 文件。这并不容易,但如果你 google "vba parse json" 你会找到一些解决方案(它通常需要导入一些库并使用其他人的代码作为起点)

希望您找到正确的解决方案,如果您找到了,可能值得分享,因为我相信会有其他人遇到同样的问题。

https://timezonedb.com/references/convert-time-zone 的 API 确实是获取正确全球 timetimezone 的好地方, 和 两个位置之间的时区偏移,考虑到 past/future 夏令时变化。

您建议的仅指定时区缩写的方法(例如 "convert PST to EST")的一个问题是 API 占用了您的时区 字面意思,即使它们不正确。

因此,如果多伦多目前在 EDT but you specify EST,您可能会得到不正确的时间。使用 "full names" 和 (UTC-08:00) Pacific Time (US & Canada) 一样会有同样的问题。

一种解决方法是指定时区名称,例如 America/Vancouver(如所列 here),或者使用适当的参数指定城市、国家/地区 and/or 区域名称.

我写了一个函数来解决这个问题,但它只适用于某些国家(往下看)。


温哥华时间 11:11pm 去年万圣节多伦多几点了?

http://api.timezonedb.com/v2/convert-time-zone?key=94RKE4SAXH67&from=America/Vancouver&to=America/Toronto&time=1509516660

结果:(默认为XML,但也可以使用JSON。)

<result>
    <status>OK</status>
    <message/>
    <fromZoneName>America/Vancouver</fromZoneName>
    <fromAbbreviation>PDT</fromAbbreviation>
    <fromTimestamp>1509516660</fromTimestamp>
    <toZoneName>America/Toronto</toZoneName>
    <toAbbreviation>EDT</toAbbreviation>
    <toTimestamp>1509527460</toTimestamp>
    <offset>10800</offset>
</result>

以编程方式获取数据:

有很多选项和查找方法需要您决定,但这里有一个使用 VBA 函数的示例:

What will be the time difference between Vancouver & Berlin on Christmas Day?

Input Time: 2018-12-25 00:00:00 = Vancouver Local Unix time 1545724800

Function GetTimeZoneOffsetHours(fromZone As String, _
            toZone As String, UnixTime As Long) As Single

    Const key = "94RKE4SAXH67"
    Const returnField = "<offset>"
    Dim HTML As String, URL As String
    Dim XML As String, pStart As Long, pStop As Long

    URL = "http://api.timezonedb.com/v2/convert-time-zone?key=" & key & _
        "&from=" & fromZone & "&to=" & toZone & "&time=" & UnixTime
    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", URL, False
        .Send
        XML = .ResponseText
    End With

    pStart = InStr(XML, returnField)
    If pStart = 0 Then
        MsgBox "Something went wrong!"
        Exit Function
    End If

    pStart = pStart + Len(returnField) + 1
    pStop = InStr(pStart, XML, "</") - 1
    GetTimeZoneOffsetHours = Val(Mid(XML, pStart, pStop - pStart)) / 60
End Function


Sub testTZ()
    Debug.Print "Time Zone Offset (Vancouver to Berlin) = " & _
        GetTimeZoneOffsetHours("America/Vancouver", _
        "Europe/Berlin", 1545724800) & " hours"
End Sub

Unix/UTC Timestamps:

Unix time is defined as "the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970."

You can convert times between Unix and/or UTC or Local time at: epochconverter.com ... the site also has conversion formulas for several programming languages.

For example, the formua to convert Unix time to GMT/UTC in Excel is:

=(A1 / 86400) + 25569

您还可以下载静态文件(SQLCSV 格式)here 而不是调用 API,该页面也有示例查询。 但是请谨慎使用:使用夏令时更容易出错(如上所述)。

我创建了一个虚拟帐户来获取示例中使用的 "demo",但您应该获取自己的(免费)密钥以供长期使用。 (如果它因过度使用而被锁定,我概不负责!)


一个很好的替代时区 API 是 Google Maps Time Zone API. The difference is that you specify Latitude & Longitude. It seems to work just fine without a key You'll need to register 作为一个键。

What will the Time Zone Offset be on June 1st at the White House?

https://maps.googleapis.com/maps/api/timezone/json?location=38.8976,-77.0365&timestamp=1527811200&key={YourKeyHere}

结果:

{
   "dstOffset" : 0,
   "rawOffset" : -18000,
   "status" : "OK",
   "timeZoneId" : "America/Toronto",
   "timeZoneName" : "Eastern Standard Time"
}

The Offset will be -18000 seconds (-5 hours).


确定夏令时何时生效

下面是我放在一起的函数,因此我可以 "trust" 我从不同的 API 获得的夏令时 (DST) 值,但是(正如其他人所讨论的)规则没有pattern plus 会随着国家的不同而不断变化,甚至在世界某些地区的城镇也会不断变化,因此这仅适用于以下国家/地区:

  • 夏令时从每年三月的第二个星期日开始
  • 夏令时在每年十一月的第一个星期日结束

适用国家为巴哈马、百慕大、加拿大、古巴、海地、圣皮埃尔和美国。 (来源: Daylight saving time by country**)

Function IsDST(dateTime As Date) As Boolean

    'Returns TRUE if Daylight Savings is in effect during the [dateTime]
    'DST Start (adjust clocks forward) Second Sunday March at 02:00am
    'DST end (adjust clocks backward) First Sunday November at 02:00am

    Dim DSTStart As Date, DSTstop As Date

    DSTStart = DateSerial(Year(dateTime), 3, _
        (14 - Weekday(DateSerial(Year(dateTime), 3, 1), 3))) + (2 / 24)
    DSTstop = DateSerial(Year(dateTime), 11, _
        (7 - Weekday(DateSerial(Year(dateTime), 11, 1), 3))) + (2 / 24)
    IsDST = (dateTime >= DSTStart) And (dateTime < DSTstop)

End Function

以及我如何使用函数 IsDST*:

的几个示例
Public Function UTCtoPST(utcDateTime As Date) As Date
    'Example for 'PST' time zone, where Offset = -7 during DST, otherwise if -8

    If IsDST(utcDateTime) Then
        UTCtoPST = utcDateTime - (7 / 24)
    Else
        UTCtoPST = utcDateTime - (8 / 24)
    End If

End Function


Function UTCtimestampMStoPST(ByVal ts As String) As Date
    'Example for 'PST', to convert a UTC Unix Time Stamp to 'PST' Time Zone

    UTCtimestampMStoPST = UTCtoPST((CLng(Left(ts, 10)) / 86400) + 25569)

End Function

* Note that function IsDST is incomplete: It does not take into account the hours just before/after IsDST takes actually effect at 2am. Specifically when, in spring, the clock jumps forward from the last instant of 01:59 standard time to 03:00 DST and that day has 23 hours, whereas in autumn the clock jumps backward from the last instant of 01:59 DST to 01:00 standard time, repeating that hour, and that day has 25 hours ...but, if someone wants to add that functionality to update the function, feel free! I was having trouble wrapping my head around that last part, and didn't immediately need that level of detail, but I'm sure others would appreciate it!


最后一个选择是 API,我用它来轮询 current/future/historical weather 数据用于各种目的 — 恰好提供 时区偏移 — 是 DarkSky。

它通过 latitude/longitude 查询并且是免费的(最多 1000 calls/day)并提供 "ultra-accurate weather data"(在美国更是如此,它预测的天气精确到 分钟 平方码! — 但我对不可预测的加拿大西海岸非常准确加拿大!)

响应仅在 JSON 中,最后一行是 时区偏移与 UTC/GMT 时间。

DarkSky Sample Call:

https://api.darksky.net/forecast/85b57f827eb89bf903b3a796ef53733c/40.70893,-74.00662

It says it's supposed to rain for the next 60 hours at Stack Overflow's Head Office. ☂

...but I dunno, it looks like a pretty nice day so far! ☀

(flag)