Epoch in Lua

A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the Unix epoch. Here’s how to do it in Lua.

-- We'll use the os module for time-related functions
local os = require("os")

-- Get the current time
local now = os.time()
print(os.date("%Y-%m-%d %H:%M:%S", now))

-- Get seconds since the Unix epoch
print(now)

-- Lua doesn't have built-in functions for milliseconds or nanoseconds,
-- but we can use os.clock() for high-resolution time difference
local start = os.clock()
local clock_diff = os.clock() - start

-- Convert to milliseconds and nanoseconds
print(math.floor(now * 1000 + clock_diff * 1000))
print(math.floor(now * 1000000000 + clock_diff * 1000000000))

-- Convert integer seconds back to a time table
print(os.date("%Y-%m-%d %H:%M:%S", now))

-- Lua doesn't have a direct equivalent to Go's time.Unix(0, now.UnixNano()),
-- but we can achieve a similar result by adding the fractional part to the time
local fractional = clock_diff % 1
print(os.date("%Y-%m-%d %H:%M:%S", now + fractional))

To run the program:

$ lua epoch.lua
2023-05-24 10:15:30
1684923330
1684923330000
1684923330000000000
2023-05-24 10:15:30
2023-05-24 10:15:30

Note that Lua doesn’t have built-in functions for milliseconds or nanoseconds since the epoch. We use os.clock() to get a high-resolution time difference, which we then use to approximate milliseconds and nanoseconds. The accuracy may not be as precise as in other languages with dedicated functions for these purposes.

Next, we’ll look at another time-related task: time parsing and formatting.