Jump to content

Module:Calendar

Kuchokera ku Wikipedia

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

--[[
  __  __           _       _         ____      _                _            
 |  \/  | ___   __| |_   _| | ___ _ / ___|__ _| | ___ _ __   __| | __ _ _ __ 
 | |\/| |/ _ \ / _` | | | | |/ _ (_) |   / _` | |/ _ \ '_ \ / _` |/ _` | '__|
 | |  | | (_) | (_| | |_| | |  __/_| |__| (_| | |  __/ | | | (_| | (_| | |   
 |_|  |_|\___/ \__,_|\__,_|_|\___(_)\____\__,_|_|\___|_| |_|\__,_|\__,_|_|   

This module is intended for date conversion between Gregorian and Julian calendars

Please do not modify this code without applying the changes first at Module:Calendar/sandbox 
and testing at Module:Calendar/sandbox/testcases 

Maintainers:
* Jarekt
]]
require('strict')

local p = {}

-- Convert calendar date to "Julian day number" (jdn)
function p._date2jdn(ISOdate, gregorian)
    ISOdate = mw.text.trim(ISOdate)
    if (#ISOdate<10 or #ISOdate>11) then return nil end
    local year, month, day = ISOdate:match("^(-?%d%d%d%d)-(%d%d)-(%d%d)")
    if not year then return nil
    elseif tonumber(year) < 0 then year = year + 1 end
    local a = math.floor((14-month)/12)
    local y = year + 4800 - a
    local m = month + 12*a - 3
    local c = math.floor((153*m + 2)/5)
    local b, d
    if (gregorian or 1) > 0 then
        b = math.floor(y/4) - math.floor(y/100) + math.floor(y/400)
        d = 32045
    else
        b = math.floor(y/4)
        d = 32083
    end
    return day + c + 365*y + b - d
end

-- Convert "Julian day number" (jdn) to a calendar date
function p._jdn2date(jdn, gregorian)
    local f = jdn + 1401
    if (gregorian or 1) > 0 then
        f = f + math.floor((math.floor((4*jdn + 274277) / 146097) * 3) / 4) - 38
    end
    local e = 4*f + 3
    local g = math.floor(math.fmod(e, 1461) / 4)
    local h = 5*g + 2
    local day = math.floor(math.fmod(h,153) / 5) + 1
    local month = math.fmod(math.floor(h/153) + 2, 12) + 1
    local year = math.floor(e/1461) - 4716 + math.floor((14 - month) / 12)
    return string.format('%04d-%02d-%02d', year, month, day)
end

function p.valid_date(frame)
    if p._valid_date(frame.args[1]) then
        return 'date is valid'
    else
        return 'date is not valid'
    end
end

return p