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 17:35, 7 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
local p = {}

function parseFormat(str)
		-- {"%B %d, %Y", "%Y", "%d-%m-%Y", "%d %B %Y", "%B %Y"}
	-- {"mdy","year","iso","dmy","month and year"}
	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


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

p.parseDate = function (frame)
	local date = frame.args.date or ""
	local format = frame.args.format or ""
	-- local date = frame or ""
	-- local format = format or ""
	local first,second,third = string.match(date, "([%w%d]+)[ /-]([%w%d]+)[, /-] ?(%d+)")
	
	local fields = {first,second,third}
	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})
		return os.date(parsedFormat, time) .. " <br>"
	end
	
	 return date .. " <br>"
end

return p