如何在 Lua 5.1 中让 os.time() 在 32 位机器上兼容?

由于 2038 年问题(https://en.wikipedia.org/wiki/Year_2038_problem),在 32 位机器上调用 os.time({year=2039, month=1, day=1, hour=0, sec=1}) 后会返回 nil。如何在 lua 层面上实现兼容性,使其在 32 位机器上的结果与 64 位机器上的一致? 是否可以编写如下函数?如果不行,怎样才能实现?

local function time32Compatibility(timeTable)
    local kMaxYearIn32Bit = 2037;
    if timeTable and timeTable.year and timeTable.year >= kMaxYearIn32Bit then
        local originalTable = clone(timeTable);
        timeTable.year = kMaxYearIn32Bit;
        local deltaTime = calculateDeltaTime(timeTable,originalTable)
        return os.time(timeTable) + kMaxYearIn32Bit*;
    else
        return os.time(timeTable);
    end
end

如何编写 calculateDeltaTime() 函数?

点赞
用户6834680
用户6834680
本地变量 orig_os_time 赋值为 os.time 函数

定义函数 os.time(timeTable):
如果 timeTable 存在,则
    假设所有能被 4 整除的年份都是闰年
    定义变量 four_year_ctr,赋值为 (timeTable.year - 2000) 整除 4 的结果(向下取整)
    将 timeTable.year 减去 four_year_ctr 乘以 4
    定义变量 result,赋值为 orig_os_time(timeTable) 加上 four_year_ctr 乘以 ((365*4+1)*24*60*60)(即四年的秒数)
    将 timeTable.year 加上 four_year_ctr 乘以 4
    进行修正,处理非闰年份,如 210022002300250026002700 等等
    将 centuries 赋值为 (result - (951868800 - 12*60*60)) 整除 (25*(365*4+1)*24*60*60) 的结果(向下取整),即 20003112 点与 result 的间隔有多少个 25 倍四年的秒数
    定义变量 wrong_feb29_ctr,赋值为 (centuries * 6 + 7) 整除 8 的结果(向下取整)
    返回 result 减去 wrong_feb29_ctr 乘以 (24*60*60) 的结果(即一天的秒数),即修正后的时间戳
否则,返回 orig_os_time()

示例:
打印 os.time 函数调用的返回值,传入的参数为一个时间表,包含 year = 1002017、month = 9、day = 27、hour = 0min = 0、sec = 0
Lua 会在一百万年后仍然存活吗?
32 位的 Linux 系统会在 2038 年后仍然存活吗?
2017-09-27 07:48:10