4

Can anyone kindly enlighten me on how to get previous day's date in 'YYYY-MM-DD' format using Lua?

I.E., a snippet that will return the date of the previous day from the day during which it is run.

Dayo
  • 12,413
  • 5
  • 52
  • 67

2 Answers2

8

Try

print(os.date("%Y-%m-%d",os.time()-24*60*60))

Strictly speaking this is only guaranteed to work on a POSIX system, but it probably works in most systems.

lhf
  • 70,581
  • 9
  • 108
  • 149
  • Just FYI: this only works by assuming a particular encoding for time_t (Unix/POSIX time), which is unspecified by the C standard and is therefore unspecified by Lua. – Mud Jul 07 '12 at 21:52
  • @Mud can you please clarify? I am running Lua on a Centos 6 box and using the ngx_lua addon for nginx. Just working on a small module and need to check the previous day's date at times. what does this `time_t (Unix/POSIX time)` mean? – Dayo Jul 07 '12 at 22:00
  • 1
    @Dayo Lua is written in C. `os.time()` is a very thin wrapper for the C `time()` function which represents time via `time_t`. The underlying type and meaning of `time_t` is [*unspecified*](http://stackoverflow.com/questions/471248/what-is-ultimately-a-time-t-typedef-to). It is *almost always* an integer representing seconds, but that's a convention, not something guaranteed by the C standard (though it is guaranteed on POSIX systems). In short, Luiz confirmed what I said: it's not *guaranteed* to work, however you're unlikely to ever run into a system where it doesn't. – Mud Jul 08 '12 at 02:19
1

There is a library LuaDate which can be very helpful for Date Manipulations http://luaforge.net/projects/date/

It is very easy to use, since it is documented well!

SatheeshJM
  • 3,575
  • 8
  • 37
  • 60
  • The project website, `date.luaforge.net`, returns a 404 error. So can't find documentation. – Dayo Jul 07 '12 at 22:03
  • No No. Documentation is included within the project itself. Download it from http://files.luaforge.net/releases/date/date – SatheeshJM Jul 07 '12 at 22:04
  • I see. Thanks for the resource ... I'll bear it in mind for whenever I want to do something a bit more involved. – Dayo Jul 07 '12 at 22:10