模块:Birthday

来自维阿百科
跳转至: 导航搜索

此模块的文档可以在模块:Birthday/doc创建

local module = {}

local getArgs = require('Module:Arguments').getArgs

function module._main(args)
	args[1] = tonumber(args[1])
	args[2] = tonumber(args[2])
	-- 默认值暂时使用GMT,即不手动指定时区时维持原状;但也许改为UTC+8更合适?
	local time = os.time() + (tonumber(args.tz) or 0) * 3600
	local month = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }

	if args[1] < 1 or args[1] > 12 then
	    error('请输入正确的月份!')
	end
	
	if args[2] < 1 or args[2] > month[args[1]] then
	    error('请输入正确的日期!')
	end
	
	function isLeapYear(year)
	    local year = year or os.date('%Y', time)
	    if (year % 4 == 0) and (year % 100 ~= 0 or year % 400 == 0) then
	        return true
	    end
	    return false
	end
	
	if isLeapYear() == false then
	    month[2] = 28
	end
	
	local count = args[2]
	for i=1, args[1] - 1 do
	    count = count + month[i]
	end
	
	local year = os.date('%Y', time) + 1
	local num = tonumber(os.date('%j', time))
	
	count = count - num
	if count < 0 then
	    local foo = 0
	    if isLeapYear(year) then
	    	if (args[1] == 2 and args[2] == 29) or args[1] > 2 then
	    		foo = 1
	    	end
	    end
	    count = count + 365 + foo
	end
	
	-- 针对2月29日的计算
	if(args[1] == 2 and args[2] == 29) then
	    count = 0
	    if isLeapYear() == false or num > 60 then
	        local foo = 0
	        if isLeapYear() and num > 60 then
	            foo = 1
	        end
	        count = 365 - num + foo
	
	        while isLeapYear(year) == false do
	            count = count + 365
	            year = year + 1
	        end
	        count = count + 60
	    else
	        count = 60 - num
	    end
	    
	end
	
	count = math.floor(count)
	return count
end

function module.main(frame)
	local args = getArgs(frame, {wrappers='Template:生日倒计时'})
	return module._main(args)
end

return module