您的位置:首页 > 编程语言 > Lua

lua比较两个时间点,返回相差几天

2017-03-07 12:01 176 查看
-- 上一个时间
local lastYear = os.date("%Y", 1490889600)
local lastMonth = os.date("%m", 1490889600)
local lastDay = os.date("%d", 1490889600)
print("lastYear==="..lastYear)
print("lastMonth==="..lastMonth)
print("lastDay==="..lastDay)

-- 当前时间
local curYear = os.date("%Y", 1490976000)
local curMonth = os.date("%m", 1490976000)
local curDay = os.date("%d", 1490976000)
print("curYear==="..curYear)
print("curMonth==="..curMonth)
print("curDay==="..curDay)

--[[比较两个时间,返回相差多少时间]]
function timediff(long_time,short_time)
local n_short_time,n_long_time,carry,diff = os.date('*t',short_time),os.date('*t',long_time),false,{}
local colMax = {60,60,24,os.date('*t',os.time{year=n_short_time.year,month=n_short_time.month+1,day=0}).day,12,0}
n_long_time.hour = n_long_time.hour - (n_long_time.isdst and 1 or 0) + (n_short_time.isdst and 1 or 0) -- handle dst
for i,v in ipairs({'sec','min','hour','day','month','year'}) do
diff[v] = n_long_time[v] - n_short_time[v] + (carry and -1 or 0)
carry = diff[v] < 0
if carry then
diff[v] = diff[v] + colMax[i]
end
end
return diff
end

local n_long_time = os.date(os.time{year=curYear,month=curMonth,day=curDay,hour=0,min=0,sec=0});
local n_short_time = os.date(os.time{year=lastYear,month=lastMonth,day=lastDay,hour=0,min=0,sec=0});

local t_time = timediff(n_long_time,n_short_time);
local time_txt = string.format("%04d", t_time.year).."年"..string.format("%02d", t_time.month).."月"..string.format("%02d", t_time.day).."日   "..string.format("%02d", t_time.hour)..":"..string.format("%02d", t_time.min)..":"..string.format("%02d", t_time.sec);
print(time_txt);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: