Skip to content

Instantly share code, notes, and snippets.

Last active Aug 20, 2021
What would you like to do?
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
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;
if not pcall(function() return ffi.C.timegm end) then
time_t timegm(struct tm *timeptr);
local dst ='struct tm') -- zeroed by default
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) )
return timegm
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment