Nanfeng

Notes on software development, code, and curious ideas

Dates and Times in Lua

Lua’s os library represents timestamps with values compatible with the host C runtime. os.time() returns the current time, while os.date() formats or decomposes it.

1
2
3
local now = os.time()
print(os.date("%Y-%m-%d %H:%M:%S", now))
print(os.date("!%Y-%m-%dT%H:%M:%SZ", now)) -- UTC

Without !, formatting uses the process’s local time zone. %c, %x, and %X are locale dependent and are unsuitable for a stable data format.

Calendar tables

1
2
3
4
5
6
7
8
local timestamp = os.time({
year = 2025, month = 8, day = 20,
hour = 14, min = 30, sec = 0,
isdst = false
})

local parts = os.date("*t", timestamp)
print(parts.year, parts.month, parts.day, parts.wday)

The runtime may normalize out-of-range fields, which is convenient for some calculations but means input must be validated separately.

Durations and calendar changes

1
local elapsedSeconds = os.difftime(finishedAt, startedAt)

Adding 24 * 60 * 60 seconds is not always the same as advancing one local calendar day because daylight-saving transitions can change day length. For scheduling across time zones, store an instant plus a named time zone and use a dedicated date-time library or service with a current time-zone database.

Timestamp range and resolution are platform dependent. Use UTC and an unambiguous interchange format at system boundaries, preserve the original time-zone intent for future events, and convert to local display time only at the user interface.

+