作为插图,我想抓住(UTC( 0000 UTC在LUA中的日期和时间。
我知道这有一些答案,但它们都不是我的答案。回答此问题的一般方法是找到当地时间,然后加上或减去UTC号码,但我不知道我的操作系统时区,因为我的程序驾驶室在不同的位置运行,并且我无法从开发环境中获得时区。<<<<<<<<<<<<
不久,如何使用LUA函数获得UTC 0日期和时间?
如果您需要生成EPG,则:
local timestamp = os.time()
local dt1 = os.date( "!*t", timestamp ) -- UTC
local dt2 = os.date( "*t" , timestamp ) -- local
local shift_h = dt2.hour - dt1.hour + (dt1.isdst and 1 or 0) -- +1 hour if daylight saving
local shift_m = 100 * (dt2.min - dt1.min) / 60
print( os.date("%Y%m%d%H%M%S ", timestamp) .. string.format('%+05d' , shift_h*100 + shift_m ))
我计算了UTC时间和本地时间之间秒的差异。这是一个准则Time
类,该类应用于from_lua_time
中的eutc时间。通过使用在UTC时间上使用的os.date('!*t', time)
,该班次没有应用。
-- The number of seconds to add to local time to turn it into UTC time.
-- We need to calculate the shift manually because lua doesn't keep track of
-- timezone information for timestamps. To guarantee reproducible results, the
-- Time class stores epoch nanoseconds in UTC.
-- https://stackoverflow.com/a/43601438/30900
local utc_seconds_shift = (function()
local ts = os.time()
local utc_date = os.date('!*t', ts)
local utc_time = os.time(utc_date)
local local_date = os.date('*t', ts)
local local_time = os.time(local_date)
return local_time - utc_time
end)()
-- Metatable for the Time class.
local Time = {}
-- Private function to create a new time instance with a properly set metatable.
function Time:new()
local o = {}
setmetatable(o, self)
self.__index = self
self.nanos = 0
return o
end
-- Parses the Lua timestamp (assuming local time) and optional nanosec time
-- into a Time class.
function from_lua_time(lua_ts)
-- Clone because os.time mutates the input table.
local clone = {
year = lua_ts.year,
month = lua_ts.month,
day = lua_ts.day,
hour = lua_ts.hour,
min = lua_ts.min,
sec = lua_ts.sec,
isdst = lua_ts.isdst,
wday = lua_ts.wday,
yday = lua_ts.yday
}
local epoch_secs = os.time(clone) + utc_seconds_shift
local nanos = lua_ts.nanosec or 0
local t = Time:new()
local secs = epoch_secs * 1000000000
t.nanos = secs + nanos
return t
end
function Time:to_lua_time()
local t = os.date('!*t', math.floor(self.nanos / 1000000000))
t.yday, t.wday, t.isdst = nil, nil, nil
t.nanosec = self.nanos % 1000000000
return t
end