FANDOM


--<nowiki>
local p = {}
local getArgs = require("Dev:Arguments").getArgs
local datecalc = require("Dev:Datecalc")
local userError = require('Dev:User error')
 
-- agerange: given two years, return the range of possible ages.
-- If only one year is given, assume the birth was sometime during that year
-- examples:
-- {{#invoke:Date|agerange|1973}} yields "1973 (age 42–43)"
-- {{#invoke:Date|agerange|1973|1974}} yields "1973–1974 (age 41–43)"
function p.agerange(frame)
    local args = getArgs(frame)
    return p._agerange(args[1], args[2])
end
 
function p._agerange(year1, year2)
    if not year2 then
        year2 = year1
    end
 
    local year1, year2 = tonumber(year1), tonumber(year2)
    if not year1 or not year2 then
        return userError('Invalid year', 'Pages with script errors')
    end
    if (year2 < year1) then
        local yeartmp = year2
        year2 = year1
        year1 = yeartmp
    end
    local date1 = { year=year1, month=1, day=1 }
    local date2 = { year=year2, month=12, day=31 }
    local now = os.date('*t')
 
    local age1 = now.year - date1.year
    local age2 = now.year - date2.year
    if now.month < date2.month or
            (now.month == date2.month and now.day < date2.day) then
        age2 = age2 - 1
    end
 
    if (age1 < 0) then
        age1 = 0
    end
    if (age2 < 0) then
        age2 = 0
    end
    local result
    if year1 == year2 then
        result = year1
    else
        result = year1 .. '–' .. year2
    end
    result = result .. ' (age ' .. age2
    if (age1 == age2) then
        return result .. ')'
    else
        return result .. '–' .. age1 .. ')'
    end
end
 
-- countdown: Shows the number of days until the specified date.
-- Replaces "%d" in message1 with the number of days.
-- If the date is already here, print message2.
-- The function also replaces "days" with "day" if one day is remaining.
-- example:
-- {{#invoke:Date|countdown|2017/01/06|%d days until something|it's over}}
-- returns something like "117 days until something", or "it's over"
function p.countdown(frame)
    local args = getArgs(frame)
    return p._countdown(args[1], args[2], args[3])
end
 
function p._countdown(day, message1, message2)
    days=datecalc.main({'diff',day})
    if not string.find(message1, '%%d') then
        return userError('Use "%d" in the second parameter to designate where to put the number of days remaining', 'Pages with script errors')
    end
    if days > 0 then
        if days == 1 then
            message1 = string.gsub(message1, 'days', 'day')
        end
        -- parentheses here to remove the pesky second return value
        -- from gsub
        return (string.gsub(message1, '%%d', days))
    else
        return message2
    end
end
 
return p
--</nowiki>