Jump to content

Module:Sandbox/Artbarte/Dates

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Artbarte (talk | contribs) at 20:48, 8 November 2018. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
-- Artbarte Google Code-in, Date formatting
-- WIP

-- @TODO
-- Handle (certain) and sometime around

local p = {}

-- Takes string | returns format string to be applied to os.date() OR nil
function parseFormat(str)
	local formats = {mdy = "%B %d, %Y",year = "%Y",iso = "%Y-%m-%d",dmy = "%d %B %Y"}
	formats["month and year"] = "%B %Y"
	
	for k,v in pairs(formats) do
		if string.lower(str) == k then
			return v
		end
	end
	return nil
end

-- Takes string | returns integer of month OR nil
function parseMonth(str)
	str = string.lower(str)
	local months = {{"January","jan"},
					{"February","feb"},
					{"March","mar"},
					{"April","apr"},
					{"May","may"},
					{"June","jun"},
					{"July","jul"},
					{"August","aug"},
					{"September","sep"},
					{"October","oct"},
					{"November","nov"},
					{"December","dec"},
					}
					
	for i,v in ipairs(months) do
		if str == string.lower(v[1]) or str == v[2] then
			return i
		end
	end
	return nil
end

function checkIfCirca (str)
	local dateString = str
	local circa = false
	local circaStrings = {"(uncertain) ", "sometime ", "around "}
	for i,v in ipairs(circaStrings) do
		dateString, matches = string.gsub(string.lower(dateString) , v, "")
		if  matches == 1 then
			circa = true
		end
	end
	return circa, dateString
	end

p.parseDate = function (frame)
	local date = frame.args.date or ""
	local format = frame.args.format or ""
	local circa = false
	local returnMsg = ""
	
	-- circa, date = checkIfCirca(date)
	local first,second,third = string.match(date, "([%w%d]+)[ /-]([%w%d]+)[, /-] ?(%d+)")

	local fields = {}
	if first ~= nil then table.insert(fields,first) else return "Invalid input <br>" end
	if second ~= nil then table.insert(fields,second) end
	if third ~= nil then table.insert(fields,third) end
	
	mw.logObject(fields)


	local day,month,year
	
	for i,v in ipairs(fields) do
		local parsedMonth = parseMonth(v)
		if parsedMonth ~= nil then
			month = parsedMonth
		elseif tonumber(v) > 31 then -- year only
			year = v
		elseif tonumber(v) > 12 then -- day only
			day = v
		elseif month == nil then
			month = v
		else
			day = v
		end
	end
	
	-- if day == nil or month == nil or year == nil then 
	-- 	return "Invalid input"
	-- end

	parsedFormat = parseFormat(format)
	if parsedFormat ~= nil then
		local time = os.time({month=month,day=day,year=year})
		returnMsg = os.date(parsedFormat, time) .. " <br>"
	end
	
	 if circa then 
	 	return "circa" .. returnMsg
	else
		return returnMsg
	end
	 
end

return p