Jump to content

Module:Birth based on age as of dates

From Wikipedia, the free encyclopedia
local yesno = require('Module:Yesno')

local p = {} --p stands for package

function p.date( frame )
	date_latest = os.time({year = frame.args[2] - frame.args[1], month = frame.args[3], day = frame.args[4]}) --we compute the latest possible birthdate based on the first give data point
	date_earliest = os.time({year = frame.args[2] - frame.args[1] - 1, month = frame.args[3], day = frame.args[4]}) + 86402 --and the earliest (the +2 is to avoid leap seconds issues while staying in the same day)
	
	--then we loop on other given datapoints to triangulate the date
	date_latest_new = os.time({year = frame.args[6] - frame.args[5], month = frame.args[7], day = frame.args[8]})
	date_latest = math.min(date_latest, date_latest_new) --for now this only works with two dates but i can add more later
	date_earliest_new = os.time({year = frame.args[6] - frame.args[5] - 1, month = frame.args[7], day = frame.args[8]}) + 86402
	date_earliest = math.max(date_earliest, date_earliest_new)
	
	--we check if the calculated birth year is the same
	if os.date("%Y", date_earliest) == os.date("%Y", date_latest) then
		birth_year_string = os.date("%Y", date_earliest)
	elseif yesno(frame.slash or false) then
		birth_year_string = os.date("%Y", date_earliest) .. "/" .. os.date("%Y", date_latest)
	else
		birth_year_string = os.date("%Y", date_earliest) .. " or " .. os.date("%Y", date_latest)
	end
	
	--then we convert back to a time table to see if the person is past their birthday
	birthday_earliest = {year = os.date("%Y", os.time()), month = os.date("%m", date_earliest), day = os.date("%d", date_earliest)}
	birthday_latest = {year = os.date("%Y", os.time()), month = os.date("%m", date_latest), day = os.date("%d", date_latest)}
	
	if yesno(frame.noage or false) then
		full_string = birth_year_string
	else
		if os.date("%Y", date_earliest) == os.date("%Y", date_latest) then
			year_diff = os.date("%Y", os.time()) - os.date("%Y", date_latest)
			if os.time() < os.time(birthday_earliest) then
				full_string = birth_year_string .. " (age " .. year_diff-1 .. ")"
			elseif os.time() < os.time(birthday_latest) then
				full_string = birth_year_string .. " (age " .. year_diff-1 .. "–" .. year_diff .. ")"
			else
				full_string = birth_year_string .. " (age " .. year_diff .. ")"
			end
		else
			year_diff = os.date("%Y", os.time()) - os.date("%Y", date_latest)
			if os.time() < os.time(birthday_latest) then
				full_string = birth_year_string .. " (age " .. year_diff-1 .. "–" .. year_diff .. ")"
			elseif os.time() < os.time(birthday_earliest) then
				full_string = birth_year_string .. " (age " .. year_diff .. ")"
			else
				full_string = birth_year_string .. " (age " .. year_diff .. "–" .. year_diff+1 .. ")"
			end
		end
	end
	
    return full_string
end

return p