Module:TimeAgo

-- -- -- Implements --

local p = {}

-- assumes 31 days in a month -- assumes 365.25 days in a year to account for leap years local convert = {60, 3600, 86400, 604800, 2678400, 31557600}

-- used to convert units to magnitudes local magnitudes = { years = 6, months = 5, weeks = 4, days = 3, hours = 2, minutes = 1, seconds = 0 }

-- units to append to time diff local units = { {'second', 'seconds', 'second\'s', 'seconds\''}, {'minute', 'minutes', 'minute\'s', 'minutes\''}, {'hour', 'hours', 'hour\'s', 'hours\''}, {'day', 'days', 'day\'s', 'days\''}, {'week', 'weeks', 'week\'s', 'weeks\''}, {'month', 'months', 'month\'s', 'months\''}, {'year', 'years', 'year\'s', 'years\''} }

-- -- -- local function core( pos, abs_diff, magnitude, ago )

local num = math.floor( abs_diff ) local unit = 1 local plural = 1

if magnitude > 0 then num = math.floor( abs_diff / convert[magnitude] ) end

if abs_diff > 1 or abs_diff == 0 then plural = plural + 1 end

if pos then ago = ago or 'ago' else plural = plural + 2 ago = 'time' end

return abs_diff .. ' ' .. units[magnitude + 1] .. ' ' .. ago end

-- -- Compares arg1 to arg2 and returns the larger number -- local function max( arg1, arg2 ) if arg1 > arg2 then return arg1 end

return arg2 end

-- -- -- function p.ago( frame ) return p._ago( frame:getParent.args ) end

function p._ago( args ) local lang = mw.language.getLanguage local frame = mw.getCurrentFrame local cur_time = lang:formatDate( 'U' )

-- check time argument is a valid time string local no_err, time = pcall( lang.formatDate, lang, 'U', args[1] ) if not no_err then return ' some error code ' end

-- calculate time diff in seconds local diff = cur_time - time local abs_diff = math.abs( diff )

-- calculate magnitude magnitude = max( auto or 0, min or -1 )

local ret = core( ( diff > 0 ), abs_diff, magnitude, args.ago )

if yesno( args.purge ) and frame then -- @todo use mw.title for this ret = ret .. ' ([' .. frame:preprocess( '') .. ' purge]) ' end end

return p