Lua判断两个日期的关系

-- 求日期差值
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	昨天
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值