This topic contains 3 replies, has 3 voices, and was last updated by  mark.brighton 3 years, 6 months ago.

Get previous day's date in LUA

  • What is the best way to get the previous day’s date in Lua? I tried subtracting 1 from*t) table, but it doesn’t work if the current date is 01/xx/2019.

    I also tried:“%Y-%m-%d”,os.time()-24*60*60)

    but getting this error

    attempt to perform arithmetic on a userdata value

    Thank you.

    There’s an example of date math near the end of this thread. Should be easy to adapt to your needs.

    Jeff Drumm ◊ VP and COO ◊ HICG, LLC. ◊

    Hi Jeff, It worked. Thank you. You are awesome

    pastOrFuture = string.lower(pastOrFuture)
    local currrentDate =‘*t’)
    local atime = os.ts.time({year=currrentDate.year,month=currrentDate.month,,hour=0,min=0,sec=0}) — create epoch time
    local adayInSeconds = (60 * 60 * 24*NumberOfDays )
    local btime
    if(pastOrFuture ==’past’) then
    btime = atime – adayInSeconds
    btime = atime + adayInSeconds
    local adate =‘%d%m%Y’,btime)

    Thank you

    There’s a second way to solve this. The original lua os.time() (now os.ts.time() in Iguana) will deal with “improper” date tables. It’s not documented in the lua manual, but pointed out here

    So you can do this:
    date = os.time({year=2019, month=11, day=1, hour=0})
    tbl =‘*t’, date) = – 1
    newDateStr =‘%c’, os.ts.time(tbl))

    newDateStr will be “10/31/19 00:00:00”.

    This do *not* work using the Iguana implementation of os.time().

    This answer uses an undocumented lua feature. The previous answer relies on os.ts.time() returning seconds (which the lua manual explicitly doesn’t guarantee). Choose your extremely unlikely source of a future bug! 😉

You must be logged in to reply to this topic.