在lua中来回UTC日期 [英] Back and forth UTC dates in lua
问题描述
我在将Lua日期转换为时间戳然后从中获取原始日期时遇到问题.它适用于非UTC日期,但不适用于UTC.
I'm having problems converting a lua date to a timestamp and then obtaining back the original date from it. It does work for non UTC dates, but not with 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 );
哪个输出:
12
12
-=-=-
10
9
11
因此,在第二部分中,使用os.time( os.date( "!*t" ) )
获得时间戳后;我不知道如何获取原始日期.我做错了什么事?
So, in the second part, after obtaining the timestamp using os.time( os.date( "!*t" ) )
; I don't know how to obtain the original date back. What is it that I'm doing wrong?
推荐答案
在Lua中使用日期表"
让dt
成为日期表".
例如,os.date("*t")
返回的值是日期表".
Working with "date tables" in Lua
Let dt
be a "date table".
For example, a value returned by os.date("*t")
is a "date table".
如何规范化日期表"
例如,在当前时间加上1.5小时后
local dt = os.date("*t"); dt.min = dt.min + 90
您需要规范化表格字段.
How to normalize "date table"
For example, after adding 1.5 hours to the current time
local dt = os.date("*t"); dt.min = dt.min + 90
you need to normalize the table fields.
function normalize_date_table(dt)
return os.date("*t", os.time(dt))
end
此函数将返回与它的参数dt
等效的新日期表,无论dt
的内容是什么含义:它是否包含本地时间或格林尼治标准时间.
This function returns new date table which is equivalent to its argument dt
regardless of the meaning of content of dt
: whether it contains local or GMT time.
如何将Unix时间转换为本地日期表"
dt = os.date("*t", ux_time)
如何将Unix时间转换为"GMT日期表"
dt = os.date("!*t", ux_time)
如何将本地日期表"转换为Unix时间
ux_time = os.time(dt)
如何将"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)
这篇关于在lua中来回UTC日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!