How to add days to a date generated by os.date() in Lua

Viewed 918

There is a lua function called date() in the os module. Calling os.date() will give the current date and time in the format: Tue Aug 10 13:04:17 2021.

Doing it like: os.date("%x") gives us the following: 08/10/21.

Is it possible to manipulate the date function to add days to the current datetime/date returned? Something like what happens when you try to add days to a JavaScript date using .setDate() mutator. I've already had a look at How to add days in given datetime in Lua but it's not what I want to achieve.

Thanks for your assistance in advance.

2 Answers

Use os.time and compute with seconds:

t=os.time()
print(os.date("%c",t))
d=12
t=t+d*24*60*60
print(os.date("%c",t))

Interactive with io.read()...

io.write('Input how many days should added>') print(os.date('%c',os.time({year=os.date('%Y'),month=os.date('%m'),day=tonumber(os.date('%d'))+tonumber(io.read()),hour=os.date('%H'),min=os.date('%M'),sec=os.date('%S')})))

A negative number also working.
...and also what day is in 365 days later ;-)
...and of course no error or exception handling (i.e. no input, hit only RETURN)
...even a float will fail, number has to be an integer

Related