I am trying to convert os.time() into a readable date e.g 06/15/2020, but for unique reasons I do not want to use os.date(). Is there any way to do this by using math?
Why not use it though? Unless you have a valid reason for this (e.g.If os.date throws an error for value being too high or you want to implement a DateTime module or you don’t need to know what year/month it is) using maths for this is a waste of time.
There’s always a DateTime module for this, seeing the source code from here or here might help.
Instead of wasting time doing maths, use any DateTIme module available on Lua.
I’ll start you off, if you have a valid reason for using math for converting to date.
First floor divide it by 86 400
.
Second divide by days in 400 years (it’s always 146 097
), the divide the remainder by days in 100 years (common year), then divide the remainder by days in 4 years (1461) then divide by the remaining by 365
.
Third create an array of days in a month and use estimation for month and the day. Use math.floor(remainder / 32)
for bit32.rshift(remainder, 5)
(your preference) to estimate the month, you can add/subtract one if the estimation is to large/too small.
Otherwise use os.date or at least a DateTime implemention.
No need to do messy arithmetic or rely on a black box module like recommended above, just use the built-in os.date()
. os.date("!*t", os.time())
will give you a table, with keys like year, day, and month.
Quick example of how you’d get it into that format using this:
local now = os.date("!*t", os.time()) -- "!*t" just means it's utc rather than local
local formatter = "%02i" -- formatter:format() will coerce a number to be a two-digit zero-padded str
-- for example, formatter:format(2) --> 02
print(formatter:format(now.month) .. "/" .. formatter:format(now.day) .. "/" .. now.year)
This code sample prints 06/15/2020, the current date, as expected. You can switch .month
and .day
for the European version.