Reputation: 51
I have a unix timestamp coming from my mysql database, and I wanna convert it to a date, but when I try to use
local time = 1647385200000
os.date("%Y %m %d", time)
It just returns nil, and I don't really understand why, when I look at documentation it seems like it should be able to take a unix timestamp and give me a date, but idk
Thanks, Ossie
Upvotes: 0
Views: 8192
Reputation: 2793
First: The time is...
time = os.date("%H:%M:%S", os.time())
You can get current date/time in epoch...
epoch = os.time()
...and the epoch of a individual date/time with...
epoch = os.time({year = 2022, month = 3, day = 9, hour = 13, min = 10, sec = 45})
After that you can do your format with...
os.date("%Y %m %d", epoch)
@OssieFromDK - Look what os.time() returns...
> print(os.time())
1646837380
> print(os.time({year = 2022, month = 3, day = 9, hour = 13, min = 10, sec = 45}))
1646827845
You see? - Epoch without milliseconds has currently 10 digits.
( Can be 0 and also negativ for birthday/history dates before 1970 )
Also the errormessage from os.date() tells me...
> os.date(_, 1647385200000)
stdin:1: bad argument #2 to 'date' (time out-of-bounds)
stack traceback:
[C]: in function 'os.date'
stdin:1: in main chunk
[C]: in ?
...that the number is not in known range of os.date()
A simple and safer way in your case to cut down to 10 digits is...
> time = 1647385200000
-- Next convert and cut down even if time is a float/integer/string
> print(os.date(_, tostring(time):sub(1, 10)))
Wed Mar 16 00:00:00 2022
...os.date() fortunately accepts a string.
When it can be translated to an integer (Autoconversion by Lua).
Simple dividing could lead to a float number and os.date() dont accept that...
> time = 1647385200123 / 1000
> print(os.date(_, time))
stdin:1: bad argument #2 to 'date' (number has no integer representation)
stack traceback:
[C]: in function 'os.date'
stdin:1: in main chunk
[C]: in ?
> print(math.type(time))
float
> print(time)
1647385200.123
( All above is done in an interactive Lua console - Should work from 5.1 upwards )
Upvotes: 1