モジュール:AgeInDays

出典: 謎の百科事典もどき『エンペディア(Enpedia)』
ナビゲーションに移動 検索に移動

ここに呼び出す説明文 『 モジュール:AgeInDays/doc 』 が作成されていません。

local p = {}

function p.main(frame)
	local birth = frame.args[1] or ""
	local death = frame.args[2] or ""  -- 第2引数を「没年月日」として扱う

	-- タグ除去
	local function stripTags(text)
		text = mw.ustring.gsub(text, "<ref[^>]*>.-</ref>", "")
		text = mw.ustring.gsub(text, "<ref[^>]*/>", "")
		text = mw.ustring.gsub(text, "<[^>]+>", "")
		return text
	end

	birth = stripTags(birth)
	death = stripTags(death)

	-- 不確定記号が含まれているかチェック(?半角全角)
	local uncertain = false
	if mw.ustring.find(birth, "[??]") or mw.ustring.find(death, "[??]") then
		uncertain = true
	end

	-- 不確定記号は計算用に除去
	birth = mw.ustring.gsub(birth, "[??*・]", "")
	death = mw.ustring.gsub(death, "[??*・]", "")

	-- 誤記補正:「年年日」を「年月日」に修正
	birth = mw.ustring.gsub(birth, "(%d+)年(%d+)年(%d+)日", "%1年%2月%3日")
	death = mw.ustring.gsub(death, "(%d+)年(%d+)年(%d+)日", "%1年%2月%3日")

	-- 年月日を取り出す関数
	local function parseYMD(text)
		local y = string.match(text, "(%d+)年")
		local m = string.match(text, "(%d+)月")
		local d = string.match(text, "(%d+)日")
		if y and m and d then
			return tonumber(y), tonumber(m), tonumber(d)
		end
		return nil
	end

	local by, bm, bd = parseYMD(birth)
	local dy, dm, dd = parseYMD(death)

	-- 誕生日が不完全なら「?歳?日」
	if not (by and bm and bd) then
		return "?歳?日"
	end

	-- 没年月日が入力されていなければ現在日付を使う
	if not (dy and dm and dd) then
		local now = os.date("*t")
		dy = now.year
		dm = now.month
		dd = now.day
	end

	-- Unixタイムスタンプ作成
	local birthTS = os.time{year = by, month = bm, day = bd}
	local deathTS = os.time{year = dy, month = dm, day = dd}

	if deathTS < birthTS then
		return "(未来日)"
	end

	-- 満年齢計算
	local years = dy - by
	if dm < bm or (dm == bm and dd < bd) then
		years = years - 1
	end

	-- 誕生日直後からの経過日数
	local latestBirthdayTS = os.time{year = by + years, month = bm, day = bd}
	local days = math.floor((deathTS - latestBirthdayTS) / 86400)

	local result = string.format("%d歳%d日", years, days)

	-- 不確定マークを末尾に付与
	if uncertain then
		result = result .. "?"
	end

	return result
end

return p