Time Formatting Parsing in Lua
Lua supports time formatting and parsing, but it doesn’t have built-in functions as extensive as Go’s. We’ll use the os.date
and os.time
functions for formatting and parsing time.
-- We'll use the os library for time functions
local os = require("os")
-- Here's a basic example of formatting the current time
local current_time = os.time()
print(os.date("%Y-%m-%dT%H:%M:%S", current_time))
-- Time parsing in Lua requires a bit more work
local function parse_time(timestr, format)
local pattern = "(%d+)%-(%d+)%-(%d+)T(%d+):(%d+):(%d+)"
local year, month, day, hour, min, sec = timestr:match(pattern)
return os.time({year=year, month=month, day=day, hour=hour, min=min, sec=sec})
end
local parsed_time = parse_time("2012-11-01T22:08:41", "%Y-%m-%dT%H:%M:%S")
print(os.date("%c", parsed_time))
-- Custom formatting examples
print(os.date("%I:%M%p", current_time))
print(os.date("%a %b %d %H:%M:%S %Y", current_time))
print(os.date("%Y-%m-%dT%H:%M:%S", current_time))
-- For parsing custom formats, you'd need to write custom parsing functions
-- For purely numeric representations, you can use string formatting
local t = os.date("*t", current_time)
print(string.format("%d-%02d-%02dT%02d:%02d:%02d-00:00",
t.year, t.month, t.day, t.hour, t.min, t.sec))
-- Error handling in parsing
local function safe_parse(timestr, format)
local success, result = pcall(parse_time, timestr, format)
if success then
return result
else
return nil, "Error parsing time: " .. result
end
end
local _, err = safe_parse("8:41PM", "%Y-%m-%dT%H:%M:%S")
print(err)
In Lua, time formatting and parsing are less standardized than in some other languages. The os.date
function provides basic formatting capabilities, while parsing often requires custom implementation.
To run this program, save it as time_formatting_parsing.lua
and use:
$ lua time_formatting_parsing.lua
This will output the formatted times and any parsing errors.
Note that Lua’s time functions might behave differently across different operating systems and Lua versions. The example above should work on most systems, but you may need to adjust it for specific requirements or environments.