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 os.date(*t) table, but it doesn’t work if the current date is 01/xx/2019.

I also tried:

os.date(“%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. ◊ http://www.hicgrp.com

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

pastOrFuture = string.lower(pastOrFuture)
local currrentDate = os.date(‘*t’)
local atime = os.ts.time({year=currrentDate.year,month=currrentDate.month,day=currrentDate.day,hour=0,min=0,sec=0}) — create epoch time
local adayInSeconds = (60 * 60 * 24*NumberOfDays )
local btime
if(pastOrFuture ==’past’) then
else
end
end

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 http://lua-users.org/wiki/DealingWithDateTime.

So you can do this:
date = os.time({year=2019, month=11, day=1, hour=0})
tbl = os.date(‘*t’, date)
tbl.day = tbl.day – 1
newDateStr = os.ts.date(‘%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.