时间操作
在 Lua 中,函数 time、date 和 difftime 提供了所有的日期和时间功能。
在 OpenResty 的世界里,不推荐使用这里的标准时间函数, 因为这些函数通常会引发不止一个昂贵的系统调用,同时无法为 LuaJIT JIT 编译,对性能造成较大影响。 推荐使用 ngx_lua 模块提供的带缓存的时间接口, 如 ngx.today, ngx.time, ngx.utctime, ngx.localtime, ngx.now, ngx.http_time,以及 ngx.cookie_time 等。
一)os.time ([table])
它会返回当前的时间和日期的时间戳(精确到秒),如赋值table,表示此table指定日期的时间戳
字段名称 取值范围
year 四位数字
month 1--12
day 1--31
hour 0--23
min 0--59
sec 0--59
isdst boolean(true表示夏令时)对于 time 函数,如果参数为 table,那么 table 中必须含有 year、month、day 字段。
其他字缺省时段默认为中午(12:00:00)。
print(os.time())
a = { year = 2018, month = 1, day = 30, hour = 0, min = 0, sec = 0 }
print(os.time(a)) 时间戳的是以计算机最小时间和指定时间之间相差的秒数,计算机最小时间为1970-1-1 00:00:00(美国时区), 针对中国时区就是1970-1-1 08:00:00
输出的就是1秒
二)os.difftime (t2, t1)
返回 t1 到 t2 的时间差,单位为秒。
三)os.date ([format [, time]])
把一个表示日期和时间的数值,转换成更高级的表现形式。
示例:
结果:
示例:
结果:
Last updated
Was this helpful?