Created
August 6, 2015 16:49
-
-
Save markuman/e96d04139cd8acc33604 to your computer and use it in GitHub Desktop.
date string to unixtime in redis with lua
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just reverse the calculation :)