来自lua的UTC日期

Jav*_* Mr 3 lua date utc

我在将lua日期转换为时间戳然后从中获取原始日期时遇到问题.它适用于非UTC日期,但不适用于UTC.

目前我的示例代码是:

local dt1 = os.date( "*t" );
print( dt1.hour );

local dt2 = os.date( "*t", os.time( dt1 ) );
print( dt2.hour );

print( "-=-=-" );

local dt1 = os.date( "!*t" );
print( dt1.hour );

local dt2 = os.date( "!*t", os.time( dt1 ) );
print( dt2.hour );

local dt2 = os.date( "*t", os.time( dt1 ) );
print( dt2.hour );
Run Code Online (Sandbox Code Playgroud)

产生输出:

12
12
-=-=-
10
9
11
Run Code Online (Sandbox Code Playgroud)

所以,在第二部分中,在获取时间戳后使用os.time( os.date( "!*t" ) ); 我不知道如何获得原始日期.我做错了什么?

Ego*_*off 5

在Lua中使用"日期表"

让我们dt成为"日期表".
例如,返回的值os.date("*t")是"日期表".


如何规范化"日期表"
例如,在将1.5小时添加到当前时间后,
local dt = os.date("*t"); dt.min = dt.min + 90
您需要规范化表字段.

function normalize_date_table(dt)
   return os.date("*t", os.time(dt))
end
Run Code Online (Sandbox Code Playgroud)

此函数返回新的日期表,该日期表与其参数等效,dt无论内容的含义如何dt:是否包含本地或GMT时间.


如何将Unix时间转换为"本地日期表"

dt = os.date("*t", ux_time)
Run Code Online (Sandbox Code Playgroud)

如何将Unix时间转换为"GMT日期表"

dt = os.date("!*t", ux_time)
Run Code Online (Sandbox Code Playgroud)

如何将"本地日期表"转换为Unix时间

ux_time = os.time(dt)
Run Code Online (Sandbox Code Playgroud)

如何将"GMT日期表"转换为Unix时间

-- for this conversion we need precalculated value "zone_diff"
local tmp_time = os.time()
local d1 = os.date("*t",  tmp_time)
local d2 = os.date("!*t", tmp_time)
d1.isdst = false
local zone_diff = os.difftime(os.time(d1), os.time(d2))
-- zone_diff value may be calculated only once (at the beginning of your program)

-- now we can perform the conversion (dt -> ux_time):
dt.sec = dt.sec + zone_diff
ux_time = os.time(dt)
Run Code Online (Sandbox Code Playgroud)