lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


You can easily calculate it from first principles:

-- forward declaration
local timegm

do
    -- offset in days for each month (starts in March)
    local month_off = { 0, 31, 61, 92, 122, 153, 184, 214, 245, 275, 306, 337 }
    -- length of 1 year, 4 years, etc
    local Y1 = 365
    local Y4 = 4*Y1+1
    local Y100 = 25 * Y4 - 1
    local Y400 = 4 * Y100 + 1
    -- offset of 1970-01-01 (calculated below)
    local epoch_offset = 0

    -- the conversion of UTC to a utc value, assuming time values
    -- are represented in seconds from an arbitrary point in time
    function timegm(yy, mm, dd, h, m, s)
assert(yy >= 1)
-- we start the year in March (day after a possible leap day)
if mm >= 3 then
   assert(mm <= 12)
   mm = mm - 2
else
   assert(mm >= 1)
   mm = mm + 10
   yy = yy - 1
end
-- calculate number of days
local dn = (yy // 400) * Y400; yy = yy % 400
dn = dn + (yy // 100) * Y100; yy = yy % 100
dn = dn + (yy // 4) * Y4; yy = yy % 4
dn = dn + yy * Y1
dn = dn + month_off[mm] + (dd - 1)
return ((dn * 24 + h) * 60 + m) * 60 + s - epoch_offset
    end
    -- fix epoch offset
    local epoch = os.date("!*t", 0)
    epoch_offset = timegm(epoch.year, epoch.month, epoch.day, epoch.hour, epoch.min, epoch.sec)
end

local now = os.time()
local t = os.date("!*t", now)
local current_time = timegm(t.year, t.month, t.day, t.hour, t.min, t.sec)

-- should print the same values
print(current_time, now)


On Tue, Mar 28, 2017 at 1:02 PM, Roberto Ierusalimschy <roberto@inf.puc-rio.br> wrote:
> Your workaround ("compute things twice") will deal with that problem,
> though, it just feels like a... workaround :)

Well, it is a workaround :-) The point is whether it works.

-- Roberto




--
--