You are browsing a read-only backup copy of Wikitech. The live site can be found at wikitech.wikimedia.org

Module:Days since incidents/since

From Wikitech-static
Jump to navigation Jump to search

Documentation for this module may be created at Module:Days since incidents/since/doc (Test casesTest results)

local function is_leap_year(year)
    -- Return true if year is a leap year, assuming Gregorian calendar.
    return year % 4 == 0 and (year % 100 ~= 0 or year % 400 == 0)
end

local function gsd(year, month, day)
    -- Return the Gregorian serial day (an integer >= 1) for the given date,
    -- or return nil if the date is invalid (only check that year >= 1).
    -- This is the number of days from the start of 1 AD (there is no year 0).
    -- This code implements the logic in [[w:Template:Gregorian serial date]].
    if not year or year < 1 then
        return nil
    end
    local floor = math.floor
    local days_this_year = (month - 1) * 30.5 + day
    if month > 2 then
        if is_leap_year(year) then
            days_this_year = days_this_year - 1
        else
            days_this_year = days_this_year - 2
        end
        if month > 8 then
            days_this_year = days_this_year + 0.9
        end
    end
    days_this_year = floor(days_this_year + 0.5)
    year = year - 1
    local days_from_past_years = year * 365
        + floor(year / 4)
        - floor(year / 100)
        + floor(year / 400)
    return days_from_past_years + days_this_year
end

local function age_days(frame)
    local date = tostring(frame.args[1])
    local year = tonumber(mw.ustring.sub(date, 1, 4))
    local month = tonumber(mw.ustring.sub(date, 5, 6))
    local day = tonumber(mw.ustring.sub(date, 7, 8))
    local to = gsd(year, month, day)
    local d = os.date('!*t')
	local from = gsd(d.year, d.month, d.day)
	return from - to
end

return { age_days = age_days }