Module:Date difference

From NPOWiki
Jump to navigation Jump to search

Documentation for this module may be created at Module:Date difference/doc

local time = mw.language.getContentLanguage()
local p = {}

function p.main(frame)
	return p.call(frame:getParent().args)
end

function p.call(args)
	local startDate, startUnix
	local endDate, endUnix
	local isValid
	local diff
	if not args[1] or args[1] == '' then
		return '<span class="error">Date: First parameter required</span>'
	end
	if args[3] and args[3] ~= '' then
		return '<span class="error">Date: Too many parameters</span>'
	end
	if args[2] and args[2] ~= '' then
		endDate = args[2]
	else
		endDate = ''
	end
	startDate = args[1]
	--formatDate works same as #time, U is Unix time. Have to pass instance to pcall.
	--Passing empty string gets current time.
	isValid, startUnix = pcall(time.formatDate, time, 'U', startDate)
	if not isValid then
		return '<span class="error">Invalid date: ' .. startDate .. '</span>'
	end
	isValid, endUnix = pcall(time.formatDate, time, 'U', endDate)
	if not isValid then
		return '<span class="error">Invalid date: ' .. endDate .. '</span>'
	end
	startUnix = tonumber(startUnix)
	endUnix = tonumber(endUnix)
	if startUnix > endUnix then
		return '<span class="error">Invalid date range: ' .. startDate .. ' to ' .. endDate .. '</span>'
	end
	diff = endUnix - startUnix
	return math.floor(diff / 86400)
end

return p