Datetime 基于UTC获取未来事件的本地时间
我正在编写一个脚本,可以在社区谷歌日历上查找事件(使用东部时区),并成功地将其转换为本地用户的时区。因为它是一个社区谷歌日历,所以我无法设置显示为UTC的时间,这在理论上会使这变得容易得多。以下是我尝试创建的一个分步过程:Datetime 基于UTC获取未来事件的本地时间,datetime,lua,timezone,date-formatting,Datetime,Lua,Timezone,Date Formatting,我正在编写一个脚本,可以在社区谷歌日历上查找事件(使用东部时区),并成功地将其转换为本地用户的时区。因为它是一个社区谷歌日历,所以我无法设置显示为UTC的时间,这在理论上会使这变得容易得多。以下是我尝试创建的一个分步过程: 从谷歌日历中获取活动时间(东部时间)。使用API和json格式很容易做到这一点 使用谷歌地图API获取基于事件时间的东部时区偏移量。同样,这很容易做到 将事件时间从Eastern转换为UTC,我认为这是通过将偏移量添加到事件时间来实现的 根据未来日期计算本地时区/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))
到
我明白了
这也是不正确的
这个脚本哪里出了问题?作为旁注,异步是一个客户端依赖项,但它本质上是http.request
将事件时间从Eastern转换为UTC,我认为这是通过将偏移量添加到事件时间来实现的
减法
时间戳中显示的偏移量是有符号的数字。它已经被“添加”到UTC以生成本地时间,因此反向操作将是减去它。如果
-0400
为负,则需要减去负4小时才能转换回UTC。能否提供/检查脚本中各种变量的输出是否正确?“将事件时间从东部转换为UTC,我认为这是通过将偏移量添加到事件时间来完成的。”实际上,减法。偏移量是有符号的,-0400
是负数,所以需要减去负4小时。@Michael sqlbot。。。我相信你解决了这个问题。如果你能回答这个问题,我会给你应得的荣誉。我不敢相信我之前没有注意到!
return os.date("%A, %B %d %Y at %I:%M%p", (utc_event_time+localoffset))
Saturday, October 31 2015 at 04:15AM