Jump to content

Module:Sandbox/R1F4T

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by R1F4T (talk | contribs) at 09:51, 23 April 2025. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
local p = {}
local getArgs = require('Module:Arguments').getArgs
local timestamp = require('Module:Bengali Unix Timestamp').main
-- Return true if Bengali year is leap
local function isLeapYear(year)
	return ((year - 594) % 4 == 0)
end
local function format_date(day, month, year, format)
    local components = { d = day, m = month, y = year }
    local result = {}

    for i = 1, #format do
        local char = format:sub(i, i)
        if components[char] then
            table.insert(result, components[char])
        else
            table.insert(result, char)
        end
    end

    return table.concat(result)
end
local BN_MONTH = {
	[1] = "Boisakh",
	[2] = "Joishtho",
	[3] = "Ashar",
	[4] = "Shrabon",
	[5] = "Bhadro",
	[6] = "Ashshin",
	[7] = "Kartik",
	[8] = "Ogrohayon",
	[9] = "Poush",
	[10] = "Magh",
	[11] = "Falgun",
	[12] = "Chaitro"
}
function p.main(frame)
	local args = getArgs(frame)
	local input1 = args[1] or ''
	local input2 = args[2] or ''

	local format, dateInput

	-- Check if input1 looks like a date (simple pattern check)
	if input1:match("^%d+%-%d+%-%d+$") or input1:match("^%d+%s+%a+%s+%d+$") then
		dateInput = input1
		format = input2 ~= '' and input2 or 'm d y'
	else
		format = input1 ~= '' and input1 or 'm d y'
		dateInput = input2 ~= '' and input2 or nil
	end

	local ts, err = getTimestamp(dateInput)
	if not ts then
		return string.format("Error: %s", err or "Invalid date.")
	end

	local second = 86400
	local days = math.floor(ts / second)
	local year = 1432

	-- Bengali year calculation
	if days >= 0 then
		while true do
			local leap = isLeapYear(year) and 366 or 365
			if days < leap then break end
			days = days - leap
			year = year + 1
		end
	else
		while true do
			local leap = isLeapYear(year - 1) and 366 or 365
			if -days <= leap then
				year = year - 1
				days = days + leap
				break
			end
			days = days + leap
			year = year - 1
		end
	end

	local isLeap = isLeapYear(year)
	local monthLengths = {31,31,31,31,31,31,30,30,30,30,30, isLeap and 30 or 29}
	local month = 1

	while days >= monthLengths[month] do
		days = days - monthLengths[month]
		month = month + 1
	end

	local day = days + 1
	return format_date(day, BN_MONTH[month], year, format)
end

return p