Module:Sandbox/RexxS/Dates

From English Wikipedia @ Freddythechick
--[[
test functions related to dates
-]]

local p = {}


local function leapd(y)
	if y % 1000 == 0 then return 29 end
	if y % 100 == 0 then return 28 end
	if y% 4 == 0 then return 29 end
	return 28
end

local months = { "jan", "feb", "mar", "apr", "may", "jun",
	"jul", "aug", "sep", "oct", "nov", "dec" }
local days_in_month = { 31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
days_in_month[0] = 0
local month_idx = {}
for i, v in ipairs(months) do
	month_idx[v] = i
end

local function day_try(d, m, y)
	days_in_month[2] = leapd(y)
	if d < 1 or d > days_in_month[m] then
		return "Invalid"
	end
	return "Valid"
end

function p.dayTry(frame)
	local date = frame.args.date or mw.text.trim(frame.args[1] or "")
	if date == "" then date = "No date" end
	local d, y = date:match("(%d+)%D+(%d+)")
	local mnth = date:match("%a+") or ""
	d, y = tonumber(d) or 1, tonumber(y) or 0
	local m = month_idx[mnth:sub(1,3):lower()] or 0
	local out = date .. " = " .. d .. " -- " .. m .. " -- " .. y .. " -- " .. mnth
	out = out .. " = " .. day_try(d, m, y)
	return out .. "<br>"
end


return p