Module:AgeCalculator
Appearance
Documentation for this module may be created at Module:AgeCalculator/doc
local p = {}
-- Helper function to format singular/plural correctly
local function format_unit(value, singular, plural)
if value == 1 then
return string.format("%d %s", value, singular)
else
return string.format("%d %s", value, plural)
end
end
-- Function to calculate the difference between two dates
function p.calculate(frame)
-- Parse inputs from the template
local year1 = tonumber(frame.args[1]) -- Start year
local month1 = tonumber(frame.args[2]) -- Start month
local day1 = tonumber(frame.args[3]) -- Start day
local year2 = tonumber(frame.args[4]) or tonumber(os.date("%Y")) -- Current year
local month2 = tonumber(frame.args[5]) or tonumber(os.date("%m")) -- Current month
local day2 = tonumber(frame.args[6]) or tonumber(os.date("%d")) -- Current day
-- Validate inputs
if not (year1 and month1 and day1) then
return "Error: Invalid input. Provide at least year, month, and day for the first date."
end
-- Calculate initial year, month, and day differences
local years = year2 - year1
local months = month2 - month1
local days = day2 - day1
-- Adjust days if negative
if days < 0 then
-- Handle previous month wrapping
local prevYear, prevMonth = year2, month2 - 1
if prevMonth < 1 then
prevMonth = 12
prevYear = prevYear - 1
end
local daysInPrevMonth = os.date("*t", os.time{year = prevYear, month = prevMonth + 1, day = 0}).day
days = days + daysInPrevMonth
months = months - 1
end
-- Adjust months if negative
if months < 0 then
months = months + 12
years = years - 1
end
-- Ensure years do not go negative (for future dates)
if years < 0 then
return "Error: The input date is in the future."
end
-- Format years, months, and days with singular/plural correctly
local year_str = format_unit(years, "year", "years")
local month_str = format_unit(months, "month", "months")
local day_str = format_unit(days, "day", "days")
-- Return the result as a string with "and" before days
if years > 0 or months > 0 then
return string.format("%s, %s, and %s", year_str, month_str, day_str)
else
return string.format("%s and %s", month_str, day_str)
end
end
return p