-- 求日期差值
function timediff(long_time,short_time)
if long_time < short_time then
long_time, short_time = short_time, long_time
end
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
下面是自己添加的一个方法,
function getTimeRelation(time)
assert(time)
print("time",time)
time = tonumber(time) or 0
local nowTime = os.time()
local y1 = os.date("%Y", time)
local y2 = os.date("%Y", nowTime)
local m1 = os.date("%m", time)
local m2 = os.date("%m", nowTime)
local d1 = os.date("%d", time)
local d2 = os.date("%d", nowTime)
print("时间转换+++>>>>", os.date("%Y-%m-%d", nowTime), os.date("%Y-%m-%d", time))
if y1 == y2 and m1 == m2 then
if d1 == d2 then
return "今天"
end
if d2 - d1 == 1 then
return "昨天"
end
else
-- 求整天的时刻的差值
local temp1 = os.time({year = y1, month = m1, day = d1, hour = 12, min = 01, sec = 01})
local temp2 = os.time({year = y2, month = m2, day = d2, hour = 12, min = 01, sec = 01})
local t = timediff(temp2, temp1)
local time = t.day * 24 + t.hour
if time == 24 then
return "昨天"
end
end
return os.date("%Y-%m-%d", time)
end
测试用例
print("getTimeRelation", getTimeRelation(1612195199))
(手动设置了nowtime为:1612078996, 2021.01.31)
结果为
time 1612195199
时间转换+++>>>> 2021-01-31 2021-02-01
getTimeRelation 昨天