0

With Lua how can I get the current date-time with milliseconds.

In this format 'YYYY-MM-DD hh:mm:ss'.

shobuz
  • 11
  • 1
  • 1
  • 4

1 Answers1

3

You could take the current UNIX time with os.time() and then add the milliseconds from os.clock()

In Lua(JIT) 5.1, do this:

local date_table = os.date("*t")
local ms = string.match(tostring(os.clock()), "%d%.(%d+)")
local hour, minute, second = date_table.hour, date_table.min, date_table.sec

local year, month, day = date_table.year, date_table.month, date_table.day   -- date_table.wday to date_table.day

local result = string.format("%d-%d-%d %d:%d:%d:%s", year, month, day, hour, minute, second, ms)

print(result)
-- will print the timestamp in the format you chose with milliseconds
-- should be all good, comment on this answer if anything's wrong please c:
Pawan Kumar
  • 113
  • 5
Cryogenic
  • 81
  • 7
  • I do have to say though, if you're looking for an actually formatted-answer, as in doing all the neat stuff like adding 0's before something if it's less than 10, you could just manually check the variables. – Cryogenic Dec 22 '16 at 22:20
  • I'd also like to add that I have, indeed, manually checked this function. Other than some simple neat formatting stuff (which you can easily add with (else)if statements) like mentioned above, this works perfectly and should suit your needs. Please message me if you'd like any changes, thanks! c: – Cryogenic Dec 22 '16 at 22:22
  • Actually, no, wait, I screwed up. Turns out `os.clock()` returns centiseconds sometimes if the millisecond number ends in a 0 (1/100th not 1/1000th) as you asked. It's also *cpu time* which means that my 'solution' is inaccurate to a range of, on average 0-600milliseconds. It is your choice to use it though the **ONLY** way you can avoid this issue is if you make or load some form of C library/file which adds custom, millisecond-precision functions to Lua which brings along its own problems too. – Cryogenic Dec 22 '16 at 22:31
  • Note: "date_table.wday" is incorrect, you want "date_table.day". The former gets you the day-of-week (e.g, in [1..7]), the latter gets the day-of-month. – Stan Sieler Apr 10 '19 at 06:05