Jump to content

Module:Calendar date/recurring

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Holly Cheng (talk | contribs) at 00:10, 27 March 2019. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

--[[ 

Calculates the Gregorian date of a recurring holiday that varies year-to-year, but follows the rule "Nth [day of week] of [month]"

  "month" = month number (1 to 12)
  "weeknumber" = number of week (1 to 4, or -1 to mean "last")
  "dayofweek" = number that represents the day of the week, where 1 = Sunday and 7 = Saturday
  "year" = Gregorian calendar year
               
 ]]

require('Module:No globals')

local p = {}

function p.calculate(frame)
	local args = frame.args

	local ONE_DAY = 86400 -- number of seconds in one day
	local year = tonumber(args.year)
	local month = tonumber(args.month)
	local date = os.time{year=year, month=month, day=1}
	local dateparts = os.date("*t", date)

	-- find the first [dayofweek] of this month
	local dayofweek = tonumber(args.dayofweek)
	while dateparts["wday"] ~= dayofweek do
		date = date + ONE_DAY
		dateparts = os.date("*t", date)
	end

	-- add the correct number of weeks
	local weeknumber = tonumber(args.weeknumber)
	if weeknumber > 1 then
		date = date + ((weeknumber - 1) * (7 * ONE_DAY))
	end

	local result = os.date("%Y-%m-%d", date)
	return result

end

return p