跨小时、跨天、跨月、跨年的通用算法(包含时区的影响)

local odate       = os.date
local HOUR_S      = 3600        --1小时(秒)
local DAY_S       = 86400       --1天(秒)
local DAY_FLUSH_S = 5 * 3600    --每日跨天时间(每日5点跨天)

--获取一个类型的时间版本号
local function edition(period, time, offset, utc)
    local value = 0
    if not time or time <= 0 then
        time = os.time()
    end
    time = time + (utc*HOUR_S) - (offset or 0)
    local t = odate("*t", time)
    if period == "hour" then
        value = time // HOUR_S
    elseif period == "day" then
        value = time // DAY_S
    elseif period == "week" then
        --19700101是星期四,周日为每周第一天
        value = ((time // DAY_S) + 4) // 7
    elseif period == "month" then
        value = t.year * 100 + t.month
    elseif period == "year" then
        value = t.year
    end
    return value
end

-- 北京时间(时区:UTC+8:00)
-- 示例1
local day_version1 = edition("day", str_to_time("2024/01/06 15:51:53"), DAY_FLUSH_S, 8)
local day_version2 = edition("day", str_to_time("2024/01/06 16:05:00"), DAY_FLUSH_S, 8)
print(string.format("beijing same_day=%s(t1_weekday_version1=%s day_version2=%s)", day_version1==day_version2,day_version1, day_version2)) -- 输出 false 19728,19729

-- 示例2
day_version1 = edition("day", str_to_time("2024/01/06 04:58:53"), DAY_FLUSH_S, 8)
day_version2 = edition("day", str_to_time("2024/01/06 05:05:00"), DAY_FLUSH_S, 8)
print(string.format("beijing same_day=%s(t1_weekday_version1=%s day_version2=%s)", day_version1==day_version2,day_version1, day_version2)) -- 输出 true 19727,19728

-- 美国东部时间(时区:UTC-5:00)
-- 示例1
day_version1 = edition("day", str_to_time("2024/01/06 15:51:53"), DAY_FLUSH_S, -5)
day_version2 = edition("day", str_to_time("2024/01/06 16:05:00"), DAY_FLUSH_S, -5)
print(string.format("beijing same_day=%s(t1_weekday_version1=%s day_version2=%s)", day_version1==day_version2,day_version1, day_version2)) -- 输出 false 19728,19729

-- 示例2
day_version1 = edition("day", str_to_time("2024/01/06 04:58:53"), DAY_FLUSH_S, -5)
day_version2 = edition("day", str_to_time("2024/01/06 05:05:00"), DAY_FLUSH_S, -5)
print(string.format("beijing same_day=%s(t1_weekday_version1=%s day_version2=%s)", day_version1==day_version2,day_version1, day_version2)) -- 输出 true 19727,19728

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

奔跑的大象

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值