Module:Sandbox/RexxS/DateBC

From English Wikipedia @ Freddythechick
local p = {}

local wiki = 
{
	langcode = mw.language.getContentLanguage().code
}

-- This is used to get a date value for date_of_birth (P569), etc. which won't
-- be linked -- consolidate by testing if entity.claims[propertyID].mainsnak.datavalue.type
-- is "time". Dates and times are stored in ISO 8601 format.
p.getDateValue = function(frame)
	local propertyID = mw.text.trim(frame.args[1] or "")
	local input_parm = mw.text.trim(frame.args[2] or "")
	local date_format = mw.text.trim(frame.args[3] or "dmy")
	local date_suffix = mw.text.trim(frame.args[4] or "BC")
	if input_parm == "FETCH_WIKIDATA" then
		local entity = mw.wikibase.getEntityObject()
		if entity.claims[propertyID] ~= nil then
			local out = {}
			local dt = {}
			for k, v in pairs(entity.claims[propertyID]) do
				if v.mainsnak.snaktype == 'value' then
					-- check for negative date
					local suffix = ""
					local timestamp = v.mainsnak.datavalue.value.time
					if string.sub(timestamp, 1, 1) == '-' then
						timestamp = '+' .. string.sub(timestamp, 2)
						suffix = date_suffix
					end
					local function d(f)
						return mw.language.new(wiki.langcode):formatDate(f, timestamp) .. " " .. suffix
					end
					if date_format == "mdy" then
						out[#out + 1] = d("F j, Y")
					elseif date_format == "my" then
						out[#out + 1] = d("F Y")
					elseif date_format == "y" then
						-- suppress leading zeros in year
						local stryear = d("Y")
						while string.sub(stryear, 1, 1) == '0' do
							stryear = string.sub(stryear, 2)
						end
						out[#out + 1] = stryear
					else
						out[#out + 1] = d("j F Y")
					end
				end
			end
			return table.concat(out, ", ")
		else
			return ""
		end
	else
		return input_parm
	end
end

return p