【发布时间】:2015-10-26 01:03:23
【问题描述】:
我正在编写一个脚本,该脚本将在社区 Google 日历(使用东部时区)上查找事件并将其成功转换为本地用户的时区。因为它是一个社区 Google 日历,所以我无法将时间设置为 UTC,理论上这会使这变得容易得多。这是我尝试创建的分步过程:
- 从 Google 日历获取活动时间(东部时间)。使用 API 和 json 格式很容易做到这一点。
- 使用 Google Maps API 根据事件时间获取东部时区偏移量。同样,这很容易做到。
- 将事件时间从东部时间转换为 UTC,我相信这是通过将偏移量添加到事件时间来完成的。
- 根据未来日期计算本地时区/UTC 时区差异。
- 通过将步骤 4 的结果添加到 UTC 事件的时间来返回事件的本地时间。
但是,无论我做什么,它似乎都无法按我想要的方式工作。下面是代码:
local function get_local_time(dateTime)
local xyear, xmonth, xday = string.match(dateTime, "(%d+)%-(%d+)%-(%d+)") -- Date format is displayed as yyyy-mm-dd
local xhour, xmin = string.match(dateTime, "%a(%d+):(%d+)") -- Time format is displayed as Thh:mm
local event_time = os.time({year = xyear, month = xmonth, day = xday, hour = xhour or 23, min = xmin or 59, sec = 0}) -- Gets epoch time for event time
async_ok, async = pcall (require, "async") -- Asynchronous lookup functions
if not json then json = require 'json' end
tzpage = "https://maps.googleapis.com/maps/api/timezone/json?location=28.4158,-81.2989×tamp=" .. event_time .. "&key=" .. key -- Gets offset data for Eastern Time Zone
if async_ok then
tzrpage = async.request(tzpage, "HTTPS")
end
retval, page, status, headers, full_status = tzrpage:join()
tzrpage = nil
if status == 200 then
tzopage = json.decode(page)
end
local eastern_offset = tzopage.rawOffset+tzopage.dstOffset -- Adds the offset information together (includes Daylight Savings)
local utc_event_time = event_time+eastern_offset -- Sets UTC's time for the event
local utctime, localtime = os.date("!*t", utc_event_time), os.date("*t", utc_event_time) -- Sets table data for events based on UTC's time of the event
localtime.isdst = false
local localoffset = os.difftime(os.time(utctime), os.time(localtime)) -- Sets the time difference between UTC and local time at the time of the event UTC
return os.date("%A, %B %d %Y at %I:%M%p", (utc_event_time-localoffset)) -- Should return local time of the event
end
但是当我执行以下操作时:
print(get_local_time("2015-10-31T01:15:00"))
返回
Friday, October 30 2015 at 02:15PM
什么时候回来
Friday, October 30 2015 at 10:15PM
因为我是太平洋时间。
如果我改变了
return os.date("%A, %B %d %Y at %I:%M%p", (utc_event_time-localoffset))
到
return os.date("%A, %B %d %Y at %I:%M%p", (utc_event_time+localoffset))
我明白了
Saturday, October 31 2015 at 04:15AM
这又是不正确的。
这个脚本哪里出错了?附带说明一下,异步是一个客户端依赖项,但它本质上是 http.request。
【问题讨论】:
-
您能否提供/检查脚本内各种变量的输出是否正确?
-
“将事件时间从东部时间转换为 UTC,我相信这是通过将偏移量添加到事件时间来完成的。” 实际上,减去。偏移量有符号,
-0400是负数,所以需要减去负数 4 小时。 -
@Michael-sqlbot... 我相信你解决了这个问题。如果您将其作为答案,我将通过选择它来给予您应得的荣誉。我不敢相信我之前没有注意到这一点!
标签: datetime lua timezone date-formatting