Time in Lua

Our first example demonstrates how to work with time and durations in Lua. Here’s the full source code:

local os = require("os")
local date = os.date

-- Helper function to print
local function p(...)
    print(...)
end

-- We'll start by getting the current time.
local now = os.time()
p(date("!%Y-%m-%d %H:%M:%S", now))

-- You can build a time by providing the year, month, day, etc.
local then_time = os.time({year=2009, month=11, day=17, hour=20, min=34, sec=58})
p(date("!%Y-%m-%d %H:%M:%S", then_time))

-- You can extract the various components of the time value as expected.
local then_date = date("*t", then_time)
p(then_date.year)
p(then_date.month)
p(then_date.day)
p(then_date.hour)
p(then_date.min)
p(then_date.sec)
p(then_date.wday)  -- The day of the week (1-7, Sunday is 1)

-- These functions compare two times, testing if the first occurs before, after, or at the same time as the second, respectively.
p(then_time < now)
p(then_time > now)
p(then_time == now)

-- We can calculate the difference between two times.
local diff = os.difftime(now, then_time)
p(diff)

-- We can compute the length of the duration in various units.
p(diff / 3600)  -- Hours
p(diff / 60)    -- Minutes
p(diff)         -- Seconds

-- You can use addition or subtraction to advance or move backwards in time.
p(date("!%Y-%m-%d %H:%M:%S", then_time + diff))
p(date("!%Y-%m-%d %H:%M:%S", then_time - diff))

Let’s go through this code:

  1. We start by importing the os module, which provides time-related functions in Lua.

  2. We define a helper function p to make printing easier.

  3. We get the current time using os.time().

  4. We create a specific time using os.time() with a table of time components.

  5. We extract various components of the time using os.date("*t", time), which returns a table with the time components.

  6. We compare times using the standard comparison operators.

  7. We calculate the difference between two times using os.difftime().

  8. We show how to convert the time difference to different units.

  9. Finally, we demonstrate how to add or subtract time from a given time.

When you run this script, you’ll see output similar to this:

2023-06-10 12:34:56
2009-11-17 20:34:58
2009
11
17
20
34
58
3
true
false
false
427038298
118621.749722222
7117304.9833333
427038298
2023-06-10 12:34:56
1996-04-26 04:34:58

Note that the exact output will depend on the current time when you run the script.

In Lua, time handling is somewhat simpler compared to some other languages. It doesn’t have a separate Duration type, so we work directly with seconds for time differences. Also, Lua’s standard library doesn’t provide as many built-in time manipulation functions, so for more complex time operations, you might need to write your own functions or use additional libraries.