A GopherLua module for time and date operations in Lua scripts.
go get github.com/kerimovok/go-lua-timeimport (
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)
`)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 minutesReturns the current time as a Unix timestamp (seconds since epoch).
- Returns:
number: Unix timestamp
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 timestampformat(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 parseformat(string, optional): Time format string (default: RFC3339)
- Returns:
number: Unix timestamp (ornilon error)string(error): Error message if parsing fails
Calculates the difference between two timestamps in seconds.
- Parameters:
t1(number): First timestampt2(number): Second timestamp
- Returns:
number: Difference in seconds (t2 - t1)
Adds seconds to a timestamp.
- Parameters:
timestamp(number): Unix timestampseconds(number): Seconds to add
- Returns:
number: New timestamp
Subtracts seconds from a timestamp.
- Parameters:
timestamp(number): Unix timestampseconds(number): Seconds to subtract
- Returns:
number: New timestamp
Pauses execution for the specified number of seconds.
- Parameters:
seconds(number): Seconds to sleep
The module provides the following format constants:
time.RFC3339: RFC3339 format (e.g., "2006-01-02T15:04:05Z07:00")time.RFC3339Nano: RFC3339 with nanosecondstime.ISO8601: ISO8601 formattime.DateOnly: Date only (e.g., "2006-01-02")time.TimeOnly: Time only (e.g., "15:04:05")
- 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