Skip to content

Instantly share code, notes, and snippets.

@Mons
Last active August 20, 2021 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mons/e96867e96cabbec99b1b52fbbe815684 to your computer and use it in GitHub Desktop.
Save Mons/e96867e96cabbec99b1b52fbbe815684 to your computer and use it in GitHub Desktop.
Lua FFI implementation of timegm (convert any given date to GMT epoch timestamp)
local ffi = require 'ffi'
if not pcall(ffi.typeof, 'struct tm') then
ffi.cdef[[
struct tm {
int tm_sec;
int tm_min;
int tm_hour;
int tm_mday;
int tm_mon;
int tm_year;
int tm_wday;
int tm_yday;
int tm_isdst;
long tm_gmtoff;
char *tm_zone;
};
]]
end
if not pcall(function() return ffi.C.timegm end) then
ffi.cdef[[
time_t timegm(struct tm *timeptr);
]]
end
local dst = ffi.new('struct tm') -- zeroed by default
--[[
usage:
timegm( sec, min, hour, day, month, year )
month is month number minus one, i.e. Jan is 0 and Dec is 11
year should be year minus 1900, so 2021 should be passed as 121
]]
local function timegm(s, m, h, D, M, Y)
dst.tm_sec = s or 0
dst.tm_min = m or 0
dst.tm_hour = h or 0
dst.tm_mday = D or 0
dst.tm_mon = M or 0
dst.tm_year = Y or 0
return tonumber( ffi.C.timegm(dst) )
end
return timegm
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment