Module:Sandbox/trappist the monk/diff time

require('strict');

local lang_object = mw.getContentLanguage;

--[[--< D I F F _ D A Y S >

return difference between two date/time strings , and , in days to decimal places. Converts each date/time string to a unix timestamp (seconds), subtracts  from , divides the difference by the number of seconds in a day (86400) and returns a formatted string to decimal places. The default precision is 3 decimal places. A positive result is returned when  is the same as, or is 'later' (more recent) than, ; negative results else.

to call this from a template: where  and  are date/time strings acceptable to the MediaWiki #time parser

]]

local function diff_days (frame) local t1 = frame.args[1];													-- t1 is 'start' time local t2 = frame.args[2];													-- t2 is 'end' time local precision = tonumber (frame.args.precision) or 3;						-- number of decimal places to show; default is 3 if 0 > precision then return ' invalid precision: ' .. precision .. ' ';	end

local good; local time1, time2;															-- to hold Unix time stamps representing the dates

good, time1 = pcall (lang_object.formatDate, lang_object, 'U', t1 );		-- convert t1 value to unix timestamp if not good then return ' invalid time: ' .. t1 .. ' ';	end

good, time2 = pcall (lang_object.formatDate, lang_object, 'U', t2 );		-- convert t2 value to unix timestamp if not good then return ' invalid time: ' .. t2 .. ' ';	end

return string.format ('%.'.. precision .. 'f', (time2 - time1)/86400); end

----< E X P O R T E D  F U N C T I O N >

return { diff_days = diff_days, diff_time = diff_days }