1

I'm working with node_redis, and saving timestamps in a redis database using the standard javascript Date.now() - in miliseconds.

Then I'm running a LUA script in my database using redis' EVAL command, to cleanup old entries from the database.

Any idea how I can translate the date/time in miliseconds that is stored in the database, to a LUA date/time object?

tbkn23
  • 5,205
  • 8
  • 26
  • 46
  • 1
    You're discouraged from using system time in Lua scripts; `Things like using the system time, calling Redis random commands like RANDOMKEY, or using Lua random number generator, could result into scripts that will not always evaluate in the same way.` Perhaps you could just send the timestamp for "too old" as an argument to the Lua script, and compare it to your stored timestamps as a number? Or even use the built-in [expireat](http://redis.io/commands/expireat) function. – Linus Thiel May 07 '14 at 09:48

2 Answers2

2

Lua's os library has the date function that can be used for this. For example, to translate the JavaScript timecode 1399454674843 to a table with all the information, simply call:

local t = os.date("*t", 1399454674843 / 1000)

This will create a table with the following entries:

hour    11
min     22
wday    4
day     7
month   5
year    2014
sec     23
yday    127
isdst   true

If you need to create a formatted string instead, you can pass the format instead of *t. Check out 22.1 Date and Time of PIL.

Henrik Ilgen
  • 1,879
  • 1
  • 17
  • 35
  • I'm getting the error `(error) ERR Error running script (call to f_f6e6582ea07a265f25a764fdebf9c62e30e0aa84): user_script:1: Script attempted to access unexisting global variable 'os'` when I try to use that command... Any idea how to enable the OS feature in the redis scripts? – tbkn23 May 07 '14 at 09:34
  • You cannot access the `os` library in Redis scripts -- only `base`, `table`, `string`, `math`, `debug`, `cjson` and `cmsgpack`. – Linus Thiel May 07 '14 at 09:59
  • Well, in this case, you can also implement the gmtime function that is used by os.date() manually. Refer to [this other SO question](http://stackoverflow.com/questions/9745255/minimal-implementation-of-gmtime-algorithm) – Henrik Ilgen May 07 '14 at 15:10
0

Although Henrik's answer might work normally, since I can't use the os library in my Redis script, I had to find another solution.

Eventually the solution I found was to pass the javascript version of the cleanup date to the lua script as parameter, and then simply compared the parameter to the date in the database, without using Lua date/time objects at all.

I'll leave this question a bit longer to see if someone knows a way in which I can properly use actual Lua date/time objects in my Redis script for more complex calculations.

tbkn23
  • 5,205
  • 8
  • 26
  • 46