go-lua-time
A GopherLua module for time and date operations in Lua scripts.
Installation
go get github.com/kerimovok/go-lua-time
Usage
In Go
import (
lua "github.com/yuin/gopher-lua"
time "github.com/kerimovok/go-lua-time"
)
L := lua.NewState()
defer L.Close()
// Preload the time module
L.PreloadModule("time", time.Loader)
// Now Lua scripts can use require("time")
L.DoString(`
local time = require("time")
local now = time.now()
local formatted = time.format(now, time.RFC3339)
print(formatted)
`)
In Lua
local time = require("time")
-- Get current Unix timestamp
local now = time.now()
print("Current time:", now)
-- Format timestamp
local formatted = time.format(now, time.RFC3339)
print("Formatted:", formatted)
-- Parse time string
local timestamp, err = time.parse("2024-01-15T10:30:00Z", time.RFC3339)
if err then
error("Parse failed: " .. err)
end
-- Calculate time difference
local t1 = time.now()
time.sleep(2) -- sleep for 2 seconds
local t2 = time.now()
local diff = time.diff(t1, t2)
print("Difference:", diff, "seconds")
-- Add/subtract time
local future = time.add(now, 3600) -- add 1 hour
local past = time.sub(now, 1800) -- subtract 30 minutes
Functions
time.now()
Returns the current time as a Unix timestamp (seconds since epoch).
time.unix_nano()
Returns the current time as a Unix nanosecond timestamp.
- Returns:
number: Unix nanosecond timestamp
Formats a Unix timestamp to a string using the specified format.
- Parameters:
timestamp (number): Unix timestamp
format (string, optional): Time format string (default: RFC3339)
- Returns:
string: Formatted time string
Parses a time string and returns a Unix timestamp.
- Parameters:
str (string): Time string to parse
format (string, optional): Time format string (default: RFC3339)
- Returns:
number: Unix timestamp (or nil on error)
string (error): Error message if parsing fails
time.diff(t1, t2)
Calculates the difference between two timestamps in seconds.
- Parameters:
t1 (number): First timestamp
t2 (number): Second timestamp
- Returns:
number: Difference in seconds (t2 - t1)
time.add(timestamp, seconds)
Adds seconds to a timestamp.
- Parameters:
timestamp (number): Unix timestamp
seconds (number): Seconds to add
- Returns:
time.sub(timestamp, seconds)
Subtracts seconds from a timestamp.
- Parameters:
timestamp (number): Unix timestamp
seconds (number): Seconds to subtract
- Returns:
time.sleep(seconds)
Pauses execution for the specified number of seconds.
- Parameters:
seconds (number): Seconds to sleep
Constants
The module provides the following format constants:
time.RFC3339: RFC3339 format (e.g., "2006-01-02T15:04:05Z07:00")
time.RFC3339Nano: RFC3339 with nanoseconds
time.ISO8601: ISO8601 format
time.DateOnly: Date only (e.g., "2006-01-02")
time.TimeOnly: Time only (e.g., "15:04:05")
Notes
- All timestamps are Unix timestamps (seconds since January 1, 1970 UTC)
- Format strings use Go's time format layout (reference time: Mon Jan 2 15:04:05 MST 2006)
time.sleep() will block the Lua execution