如何在Lua5.1中的32位机器上实现os.time()兼容性?

如何在Lua5.1中的32位机器上实现os.time()兼容性?,time,lua,32-bit,year2038,Time,Lua,32 Bit,Year2038,由于2038年的问题(),我们在32位机器上调用os.time({Year=2039,month=1,day=1,hour=0,sec=1})后得到了nil。如何使其在lua层中兼容,并像在64位机器上运行一样得到结果? 编写如下函数是否可行?否则,如何实现呢 local function time32Compatibility(timeTable) local kMaxYearIn32Bit = 2037; if timeTable and timeTable.year and

由于2038年的问题(),我们在32位机器上调用os.time({Year=2039,month=1,day=1,hour=0,sec=1})后得到了nil。如何使其在lua层中兼容,并像在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()?

将年份向下移动
4*N
,然后将
N*4年的秒数添加到结果中是个好主意!还有一个问题,关于闰年。每一个能被四整除的年份都是闰年,但能被100整除的年份除外,但如果这些百年能被400整除,那么它们就是闰年。例如,1700年、1800年和1900年不是闰年,而1600年和2000年是闰年@在1970-2038之间,所有可以被4整除的年份都是闰年。非常感谢你的完整代码!但是我发现它有点问题。我已经将您的代码的结果与诸如“”之类的工具进行了比较,您的代码在年份<2100时是正确的,而在年份>=2100,月份>2时是错误的。正如我所说,我们应该考虑“除了那些可以被100整除的年份”。我找不到一个简单的方法来实现它。因为2100年不是闰年,而您的代码将其视为闰年。@youzhiwan-答案已更新。请从1970年开始测试所有可能的日期。谢谢!但这里还是有问题。当时间表={year=2100,month=3,day=1,hour=0,min=0,sec=0}时,我们就错了,应该是1。实际上,临界值很麻烦。我想问“幻数”是什么意思,比如“25*(365*4+1)”,“((世纪*6+7)/8)”等等。你能修复这个错误并写更多的评论来解释幻数吗?再次感谢。@youzhiwan-
25*(365*4+1)
是每100年的天数,
f(n)=floor((n*6+7)/8)
是一个函数,它跳过每四个增量的
n
:对于n=1,2,3,4,5,。。。f(n)的值是:1,2,3,3,4,5,6,6,7,8,9,9,。。。
local orig_os_time = os.time

function os.time(timeTable)
   if timeTable then
      -- assume that all years divisible by 4 are leap years
      local four_year_ctr = math.floor((timeTable.year - 2000) / 4)
      timeTable.year = timeTable.year - four_year_ctr * 4
      local result = orig_os_time(timeTable) + four_year_ctr * ((365*4+1)*24*60*60)
      timeTable.year = timeTable.year + four_year_ctr * 4
      -- make a correction for non-leap years 2100,2200,2300, 2500,2600,2700,...
      -- subtract ("March 1, 2000" - 12 hours) and divide by 100 "wrong" years
      -- It should work for all time zones from UTC-1200 to UTC+1200
      local centuries = math.floor((result - (951868800 - 12*60*60)) / (25*(365*4+1)*24*60*60))
      local wrong_feb29_ctr = math.floor((centuries * 6 + 7) / 8)
      return result - wrong_feb29_ctr * (24*60*60)
   else
      return orig_os_time()
   end
end

-- Example:
print(os.time{year = 1002017, month = 9, day = 27, hour = 0, min = 0, sec = 0})
-- Will Lua be alive after million years?
-- Will 32-bit Linux systems be alive after 2038?