关于日期时间:在Lua中获取特定的UTC日期和时间

Get specific UTC date and Time in Lua

作为说明,我想在LUA中获取(UTC)+0000 UTC日期和时间。

我知道有一些答案,但是没有一个不是我的答案。 解决此问题的一般方法是"查找本地时间",然后加上或减去UTC编号,但我不知道我的操作系统时区,因为我的程序室运行在不同的位置,并且无法从开发环境中获取时区。

不久,如何使用LUA函数获取UTC 0日期和时间?


如果您需要生成epg,则:

1
2
3
4
5
6
7
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类,该类应用该移位将UTC时间存储在from_lua_time中。 使用os.date('!*t', time)(适用于UTC时间)不应用该移位。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
-- 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