Lua 基础相关知识 第五期(完结)
时间戳
通过 os.time
函数,可以获取当前的时间戳。
1 2 3 4
| local time = os.time() print(time)
|
如果要指定日期,获取对应的时间戳,可以往 os.time
函数传入一个表,设定日期。
1 2 3 4 5 6 7 8 9 10 11 12
| local date = { year = 2024, month = 6, day = 9, hour = 9, min = 30, sec = 30 } local time = os.time(date) print(time)
|
注意到,如果只写了年份、月份、天数,没有小时、分钟、秒数,默认是当天中午 12 点。
1 2 3 4 5 6 7 8 9
| local date = { year = 2024, month = 6, day = 9, } local time = os.time(date) print(time)
|
日期
通过 os.date
函数,可以把时间戳转换成有格式的日期。
1 2 3 4 5 6 7 8 9 10
| local time = os.time() print(time)
local date = os.date("%Y/%m/%d %H:%M:%S", time) print(date)
|
如果不带任何参数调用 os.date
,则获取当前时间戳对应的默认日期格式。
1 2 3 4
| local date = os.date() print(date)
|
有时候,我们需要获取日期当中的某个参数,比如天数,可以把 os.date 的第一个参数改成 "*t"
,此时它会返回一个表。
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
| local time = os.time() print(time)
local dateTable = os.date("*t", time) print(dateTable)
for key, value in pairs(dateTable) do print(key, value) end
|
如果要计算多少天后的日期,可以给这个日期表中的 day 字段加上一定的天数,转成时间戳后,再格式化日期。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| local time = os.time()
local currentDate = os.date("%Y/%m/%d %H:%M:%S", time) print(currentDate)
local dateTable = os.date("*t", time) dateTable.day = dateTable.day + 100
local future = os.time(dateTable)
local futureDate = os.date("%Y/%m/%d %H:%M:%S", future)
print(futureDate)
|
时间差
通过 os.difftime
函数,计算两个时间戳之间的差值。
例如,计算一下当前时间到次日零点的秒数。
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
| local now = os.time() print(os.date("%Y/%m/%d %H:%M:%S", now))
local nowDate = os.date("*t", now) nowDate.day = nowDate.day + 1 nowDate.hour = 0 nowDate.min = 0 nowDate.sec = 0
local future = os.time(nowDate) print(os.date("%Y/%m/%d %H:%M:%S", future))
local diff = os.difftime(now, future) print(diff)
|
CPU 时间
通过 os.clock
函数,可以获取消耗的 CPU 时间,可以用在性能测试。
例如,计算一下 for 循环累加 1 亿次消耗的时间。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| local before = os.clock() print(before)
local sum = 0 for i = 1, 100000000 do sum = sum + i end
local after = os.clock() print(after)
local diff = after - before print(diff)
|