Skip to content

Instantly share code, notes, and snippets.

@markuman
Created August 6, 2015 16:49
Show Gist options
  • Save markuman/e96d04139cd8acc33604 to your computer and use it in GitHub Desktop.
Save markuman/e96d04139cd8acc33604 to your computer and use it in GitHub Desktop.
date string to unixtime in redis with lua
local function YearInSec(y)
-- returns seconds of a year
if ((y % 400) == 0) or (((y % 4) == 0) and ((y % 100) ~= 0)) then
return 31622400 -- 366 * 24 * 60 * 60
else
return 31536000 -- 365 * 24 * 60 * 60
end
end
local function IsLeapYear(y)
-- returns true of false
return ((y % 400) == 0) or (((y % 4) == 0) and ((y % 100) ~= 0))
end
local function unixtime(date)
-- date = "2013-01-13 15:45:13"
local days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
local daysec = 86400
local y,m,d,h,mi,s = date:match("(%d+)-(%d+)-(%d+)%s+(%d+):(%d+):(%d+)")
local time = 0
-- sum years
for n = 1970,(y - 1) do
time = time + YearInSec(n)
end
-- sum month
for n = 1,(m - 1) do
time = time + (days[n] * daysec)
end
-- add days
time = time + (d - 1) * daysec
-- if current year is leap year and february is in the past
-- it seems that m + 0 is much faster than tonumber(m)
-- this currently works with 5.1, 5.2 and 5.3 but in future lua versions this can be removed
if IsLeapYear(y) and (m + 0 > 2) then
time = time + daysec
end
-- add hour, minute and seconds
return time + (h * 3600) + (mi * 60) + s
end
local S = unixtime(ARGV[1]) -- this is the score, currently in date string form
return redis.call("ZADD", KEYS[1], S, ARGV[2])
@ccwxl
Copy link

ccwxl commented Aug 5, 2019

How to format the unixtime into "2013-01-13 15:45:13"?

@markuman
Copy link
Author

markuman commented Aug 5, 2019

Just reverse the calculation :)

  1. determine seconds (line 44)
  2. determine minute (line 44)
  3. determine hour (also line 44)
  4. determine day (line 34)
  5. determine month (line 29-30)
  6. determine year (line 24-25)
  7. build date string (line 20)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment