Module:Age

From Remilia Wiki
Jump to navigation Jump to search

Documentation for this module may be created at Module:Age/doc

-- Module:Age
-- Calculates age from birth date to current date
-- Used by {{Birth date and age}} template

local p = {}

-- Helper function to check if a year is a leap year
local function isLeapYear(year)
    return year % 4 == 0 and (year % 100 ~= 0 or year % 400 == 0)
end

-- Helper function to get days in a month
local function daysInMonth(year, month)
    local days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
    if month == 2 and isLeapYear(year) then
        return 29
    end
    return days[month]
end

-- Main function called by {{Birth date and age}}
function p.age_date(frame)
    local args = frame:getParent().args
    
    -- Get birth date from arguments
    local b_year = tonumber(args[1])
    local b_month = tonumber(args[2])
    local b_day = tonumber(args[3])

    -- Validate inputs
    if not b_year or not b_month or not b_day then
        return '<span class="error">Error: Incomplete date parameters</span>'
    end
    
    if b_month < 1 or b_month > 12 then
        return '<span class="error">Error: Month must be 1-12</span>'
    end
    
    if b_day < 1 or b_day > daysInMonth(b_year, b_month) then
        return '<span class="error">Error: Invalid day for given month</span>'
    end

    -- Get current date from MediaWiki
    local c_year = tonumber(mw.language.new('en'):formatDate('Y'))
    local c_month = tonumber(mw.language.new('en'):formatDate('n'))
    local c_day = tonumber(mw.language.new('en'):formatDate('j'))

    -- Calculate age
    local age = c_year - b_year
    
    -- Adjust if birthday hasn't occurred yet this year
    if c_month < b_month or (c_month == b_month and c_day < b_day) then
        age = age - 1
    end

    -- Format the birth date string
    local months = {
        "January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December"
    }
    local b_date_str = months[b_month] .. " " .. b_day .. ", " .. b_year

    -- Return formatted string with microformat markup for semantic data
    return '<span class="bday">' .. b_year .. '-' .. 
           string.format('%02d', b_month) .. '-' .. 
           string.format('%02d', b_day) .. '</span> ' ..
           '<span class="dtstart" style="display:none">' .. b_date_str .. '</span>' ..
           b_date_str .. ' <span class="noprint">(age ' .. age .. ')</span>'
end

return p