Module:Date

    From Nonbinary Wiki

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

    -- Date functions for use by other modules.
    -- I18N and time zones are not supported.
    
    local MINUS = '−'  -- Unicode U+2212 MINUS SIGN
    local floor = math.floor
    
    local Date, DateDiff, diffmt  -- forward declarations
    local uniq = { 'unique identifier' }
    
    local function is_date(t)
    	-- The system used to make a date read-only means there is no unique
    	-- metatable that is conveniently accessible to check.
    	return type(t) == 'table' and t._id == uniq
    end
    
    local function is_diff(t)
    	return type(t) == 'table' and getmetatable(t) == diffmt
    end
    
    local function _list_join(list, sep)
    	return table.concat(list, sep)
    end
    
    local function collection()
    	-- Return a table to hold items.
    	return {
    		n = 0,
    		add = function (self, item)
    			self.n = self.n + 1
    			self[self.n] = item
    		end,
    		join = _list_join,
    	}
    end
    
    local function strip_to_nil(text)
    	-- If text is a string, return its trimmed content, or nil if empty.
    	-- Otherwise return text (convenient when Date fields are provided from
    	-- another module which may pass a string, a number, or another type).
    	if type(text) == 'string' then
    		text = text:match('(%S.-)%s*$')
    	end
    	return text
    end
    
    local function is_leap_year(year, calname)
    	-- Return true if year is a leap year.
    	if calname == 'Julian' then
    		return year % 4 == 0
    	end
    	return (year % 4 == 0 and year % 100 ~= 0) or year % 400 == 0
    end
    
    local function days_in_month(year, month, calname)
    	-- Return number of days (1..31) in given month (1..12).
    	if month == 2 and is_leap_year(year, calname) then
    		return 29
    	end
    	return ({ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 })[month]
    end
    
    local function h_m_s(time)
    	-- Return hour, minute, second extracted from fraction of a day.
    	time = floor(time * 24 * 3600 + 0.5)  -- number of seconds
    	local second = time % 60
    	time = floor(time / 60)
    	return floor(time / 60), time % 60, second
    end
    
    local function hms(date)
    	-- Return fraction of a day from date's time, where (0 <= fraction < 1)
    	-- if the values are valid, but could be anything if outside range.
    	return (date.hour + (date.minute + date.second / 60) / 60) / 24
    end
    
    local function julian_date(date)
    	-- Return jd, jdz from a Julian or Gregorian calendar date where
    	--   jd = Julian date and its fractional part is zero at noon
    	--   jdz = same, but assume time is 00:00:00 if no time given
    	-- http://www.tondering.dk/claus/cal/julperiod.php#formula
    	-- Testing shows this works for all dates from year -9999 to 9999!
    	-- JDN 0 is the 24-hour period starting at noon UTC on Monday
    	--    1 January 4713 BC  = (-4712, 1, 1)   Julian calendar
    	--   24 November 4714 BC = (-4713, 11, 24) Gregorian calendar
    	local offset
    	local a = floor((14 - date.month)/12)
    	local y = date.year + 4800 - a
    	if date.calendar == 'Julian' then
    		offset = floor(y/4) - 32083
    	else
    		offset = floor(y/4) - floor(y/100) + floor(y/400) - 32045
    	end
    	local m = date.month + 12*a - 3
    	local jd = date.day + floor((153*m + 2)/5) + 365*y + offset
    	if date.hastime then
    		jd = jd + hms(date) - 0.5
    		return jd, jd
    	end
    	return jd, jd - 0.5
    end
    
    local function set_date_from_jd(date)
    	-- Set the fields of table date from its Julian date field.
    	-- Return true if date is valid.
    	-- http://www.tondering.dk/claus/cal/julperiod.php#formula
    	-- This handles the proleptic Julian and Gregorian calendars.
    	-- Negative Julian dates are not defined but they work.
    	local calname = date.calendar
    	local low, high  -- min/max limits for date ranges −9999-01-01 to 9999-12-31
    	if calname == 'Gregorian' then
    		low, high = -1930999.5, 5373484.49999
    	elseif calname == 'Julian' then
    		low, high = -1931076.5, 5373557.49999
    	else
    		return
    	end
    	local jd = date.jd
    	if not (type(jd) == 'number' and low <= jd and jd <= high) then
    		return
    	end
    	local jdn = floor(jd)
    	if date.hastime then
    		local time = jd - jdn  -- 0 <= time < 1
    		if time >= 0.5 then    -- if at or after midnight of next day
    			jdn = jdn + 1
    			time = time - 0.5
    		else
    			time = time + 0.5
    		end
    		date.hour, date.minute, date.second = h_m_s(time)
    	else
    		date.second = 0
    		date.minute = 0
    		date.hour = 0
    	end
    	local b, c
    	if calname == 'Julian' then
    		b = 0
    		c = jdn + 32082
    	else  -- Gregorian
    		local a = jdn + 32044
    		b = floor((4*a + 3)/146097)
    		c = a - floor(146097*b/4)
    	end
    	local d = floor((4*c + 3)/1461)
    	local e = c - floor(1461*d/4)
    	local m = floor((5*e + 2)/153)
    	date.day = e - floor((153*m + 2)/5) + 1
    	date.month = m + 3 - 12*floor(m/10)
    	date.year = 100*b + d - 4800 + floor(m/10)
    	return true
    end
    
    local function fix_numbers(numbers, y, m, d, H, M, S, partial, hastime, calendar)
    	-- Put the result of normalizing the given values in table numbers.
    	-- The result will have valid m, d values if y is valid; caller checks y.
    	-- The logic of PHP mktime is followed where m or d can be zero to mean
    	-- the previous unit, and -1 is the one before that, etc.
    	-- Positive values carry forward.
    	local date
    	if not (1 <= m and m <= 12) then
    		date = Date(y, 1, 1)
    		if not date then return end
    		date = date + ((m - 1) .. 'm')
    		y, m = date.year, date.month
    	end
    	local days_hms
    	if not partial then
    		if hastime and H and M and S then
    			if not (0 <= H and H <= 23 and
    					0 <= M and M <= 59 and
    					0 <= S and S <= 59) then
    				days_hms = hms({ hour = H, minute = M, second = S })
    			end
    		end
    		if days_hms or not (1 <= d and d <= days_in_month(y, m, calendar)) then
    			date = date or Date(y, m, 1)
    			if not date then return end
    			date = date + (d - 1 + (days_hms or 0))
    			y, m, d = date.year, date.month, date.day
    			if days_hms then
    				H, M, S = date.hour, date.minute, date.second
    			end
    		end
    	end
    	numbers.year = y
    	numbers.month = m
    	numbers.day = d
    	if days_hms then
    		-- Don't set H unless it was valid because a valid H will set hastime.
    		numbers.hour = H
    		numbers.minute = M
    		numbers.second = S
    	end
    end
    
    local function set_date_from_numbers(date, numbers, options)
    	-- Set the fields of table date from numeric values.
    	-- Return true if date is valid.
    	if type(numbers) ~= 'table' then
    		return
    	end
    	local y = numbers.year   or date.year
    	local m = numbers.month  or date.month
    	local d = numbers.day    or date.day
    	local H = numbers.hour
    	local M = numbers.minute or date.minute or 0
    	local S = numbers.second or date.second or 0
    	local need_fix
    	if y and m and d then
    		date.partial = nil
    		if not (-9999 <= y and y <= 9999 and
    			1 <= m and m <= 12 and
    			1 <= d and d <= days_in_month(y, m, date.calendar)) then
    				if not date.want_fix then
    					return
    				end
    				need_fix = true
    		end
    	elseif y and date.partial then
    		if d or not (-9999 <= y and y <= 9999) then
    			return
    		end
    		if m and not (1 <= m and m <= 12) then
    			if not date.want_fix then
    				return
    			end
    			need_fix = true
    		end
    	else
    		return
    	end
    	if date.partial then
    		H = nil  -- ignore any time
    		M = nil
    		S = nil
    	else
    		if H then
    			-- It is not possible to set M or S without also setting H.
    			date.hastime = true
    		else
    			H = 0
    		end
    		if not (0 <= H and H <= 23 and
    				0 <= M and M <= 59 and
    				0 <= S and S <= 59) then
    			if date.want_fix then
    				need_fix = true
    			else
    				return
    			end
    		end
    	end
    	date.want_fix = nil
    	if need_fix then
    		fix_numbers(numbers, y, m, d, H, M, S, date.partial, date.hastime, date.calendar)
    		return set_date_from_numbers(date, numbers, options)
    	end
    	date.year = y    -- -9999 to 9999 ('n BC' → year = 1 - n)
    	date.month = m   -- 1 to 12 (may be nil if partial)
    	date.day = d     -- 1 to 31 (* = nil if partial)
    	date.hour = H    -- 0 to 59 (*)
    	date.minute = M  -- 0 to 59 (*)
    	date.second = S  -- 0 to 59 (*)
    	if type(options) == 'table' then
    		for _, k in ipairs({ 'am', 'era', 'format' }) do
    			if options[k] then
    				date.options[k] = options[k]
    			end
    		end
    	end
    	return true
    end
    
    local function make_option_table(options1, options2)
    	-- If options1 is a string, return a table with its settings, or
    	-- if it is a table, use its settings.
    	-- Missing options are set from table options2 or defaults.
    	-- If a default is used, a flag is set so caller knows the value was not intentionally set.
    	-- Valid option settings are:
    	-- am: 'am', 'a.m.', 'AM', 'A.M.'
    	--     'pm', 'p.m.', 'PM', 'P.M.' (each has same meaning as corresponding item above)
    	-- era: 'BCMINUS', 'BCNEGATIVE', 'BC', 'B.C.', 'BCE', 'B.C.E.', 'AD', 'A.D.', 'CE', 'C.E.'
    	-- Option am = 'am' does not mean the hour is AM; it means 'am' or 'pm' is used, depending on the hour,
    	--    and am = 'pm' has the same meaning.
    	-- Similarly, era = 'BC' means 'BC' is used if year <= 0.
    	-- BCMINUS displays a MINUS if year < 0 and the display format does not include %{era}.
    	-- BCNEGATIVE is similar but displays a hyphen.
    	local result = { bydefault = {} }
    	if type(options1) == 'table' then
    		result.am = options1.am
    		result.era = options1.era
    	elseif type(options1) == 'string' then
    		-- Example: 'am:AM era:BC' or 'am=AM era=BC'.
    		for item in options1:gmatch('%S+') do
    			local lhs, rhs = item:match('^(%w+)[:=](.+)$')
    			if lhs then
    				result[lhs] = rhs
    			end
    		end
    	end
    	options2 = type(options2) == 'table' and options2 or {}
    	local defaults = { am = 'am', era = 'BC' }
    	for k, v in pairs(defaults) do
    		if not result[k] then
    			if options2[k] then
    				result[k] = options2[k]
    			else
    				result[k] = v
    				result.bydefault[k] = true
    			end
    		end
    	end
    	return result
    end
    
    local ampm_options = {
    	-- lhs = input text accepted as an am/pm option
    	-- rhs = code used internally
    	['am']   = 'am',
    	['AM']   = 'AM',
    	['a.m.'] = 'a.m.',
    	['A.M.'] = 'A.M.',
    	['pm']   = 'am',  -- same as am
    	['PM']   = 'AM',
    	['p.m.'] = 'a.m.',
    	['P.M.'] = 'A.M.',
    }
    
    local era_text = {
    	-- Text for displaying an era with a positive year (after adjusting
    	-- by replacing year with 1 - year if date.year <= 0).
    	-- options.era = { year<=0 , year>0 }
    	['BCMINUS']    = { 'BC'    , ''    , isbc = true, sign = MINUS },
    	['BCNEGATIVE'] = { 'BC'    , ''    , isbc = true, sign = '-'   },
    	['BC']         = { 'BC'    , ''    , isbc = true },
    	['B.C.']       = { 'B.C.'  , ''    , isbc = true },
    	['BCE']        = { 'BCE'   , ''    , isbc = true },
    	['B.C.E.']     = { 'B.C.E.', ''    , isbc = true },
    	['AD']         = { 'BC'    , 'AD'   },
    	['A.D.']       = { 'B.C.'  , 'A.D.' },
    	['CE']         = { 'BCE'   , 'CE'   },
    	['C.E.']       = { 'B.C.E.', 'C.E.' },
    }
    
    local function get_era_for_year(era, year)
    	return (era_text[era] or era_text['BC'])[year > 0 and 2 or 1] or ''
    end
    
    local function strftime(date, format, options)
    	-- Return date formatted as a string using codes similar to those
    	-- in the C strftime library function.
    	local sformat = string.format
    	local shortcuts = {
    		['%c'] = '%-I:%M %p %-d %B %-Y %{era}',  -- date and time: 2:30 pm 1 April 2016
    		['%x'] = '%-d %B %-Y %{era}',            -- date:          1 April 2016
    		['%X'] = '%-I:%M %p',                    -- time:          2:30 pm
    	}
    	if shortcuts[format] then
    		format = shortcuts[format]
    	end
    	local codes = {
    		a = { field = 'dayabbr' },
    		A = { field = 'dayname' },
    		b = { field = 'monthabbr' },
    		B = { field = 'monthname' },
    		u = { fmt = '%d'  , field = 'dowiso' },
    		w = { fmt = '%d'  , field = 'dow' },
    		d = { fmt = '%02d', fmt2 = '%d', field = 'day' },
    		m = { fmt = '%02d', fmt2 = '%d', field = 'month' },
    		Y = { fmt = '%04d', fmt2 = '%d', field = 'year' },
    		H = { fmt = '%02d', fmt2 = '%d', field = 'hour' },
    		M = { fmt = '%02d', fmt2 = '%d', field = 'minute' },
    		S = { fmt = '%02d', fmt2 = '%d', field = 'second' },
    		j = { fmt = '%03d', fmt2 = '%d', field = 'dayofyear' },
    		I = { fmt = '%02d', fmt2 = '%d', field = 'hour', special = 'hour12' },
    		p = { field = 'hour', special = 'am' },
    	}
    	options = make_option_table(options, date.options)
    	local amopt = options.am
    	local eraopt = options.era
    	local function replace_code(spaces, modifier, id)
    		local code = codes[id]
    		if code then
    			local fmt = code.fmt
    			if modifier == '-' and code.fmt2 then
    				fmt = code.fmt2
    			end
    			local value = date[code.field]
    			if not value then
    				return nil  -- an undefined field in a partial date
    			end
    			local special = code.special
    			if special then
    				if special == 'hour12' then
    					value = value % 12
    					value = value == 0 and 12 or value
    				elseif special == 'am' then
    					local ap = ({
    						['a.m.'] = { 'a.m.', 'p.m.' },
    						['AM'] = { 'AM', 'PM' },
    						['A.M.'] = { 'A.M.', 'P.M.' },
    					})[ampm_options[amopt]] or { 'am', 'pm' }
    					return (spaces == '' and '' or '&nbsp;') .. (value < 12 and ap[1] or ap[2])
    				end
    			end
    			if code.field == 'year' then
    				local sign = (era_text[eraopt] or {}).sign
    				if not sign or format:find('%{era}', 1, true) then
    					sign = ''
    					if value <= 0 then
    						value = 1 - value
    					end
    				else
    					if value >= 0 then
    						sign = ''
    					else
    						value = -value
    					end
    				end
    				return spaces .. sign .. sformat(fmt, value)
    			end
    			return spaces .. (fmt and sformat(fmt, value) or value)
    		end
    	end
    	local function replace_property(spaces, id)
    		if id == 'era' then
    			-- Special case so can use local era option.
    			local result = get_era_for_year(eraopt, date.year)
    			if result == '' then
    				return ''
    			end
    			return (spaces == '' and '' or '&nbsp;') .. result
    		end
    		local result = date[id]
    		if type(result) == 'string' then
    			return spaces .. result
    		end
    		if type(result) == 'number' then
    			return  spaces .. tostring(result)
    		end
    		if type(result) == 'boolean' then
    			return  spaces .. (result and '1' or '0')
    		end
    		-- This occurs if id is an undefined field in a partial date, or is the name of a function.
    		return nil
    	end
    	local PERCENT = '\127PERCENT\127'
    	return (format
    		:gsub('%%%%', PERCENT)
    		:gsub('(%s*)%%{(%w+)}', replace_property)
    		:gsub('(%s*)%%(%-?)(%a)', replace_code)
    		:gsub(PERCENT, '%%')
    	)
    end
    
    local function _date_text(date, fmt, options)
    	-- Return a formatted string representing the given date.
    	if not is_date(date) then
    		error('date:text: need a date (use "date:text()" with a colon)', 2)
    	end
    	if type(fmt) == 'string' and fmt:match('%S') then
    		if fmt:find('%', 1, true) then
    			return strftime(date, fmt, options)
    		end
    	elseif date.partial then
    		fmt = date.month and 'my' or 'y'
    	else
    		fmt = 'dmy'
    		if date.hastime then
    			fmt = (date.second > 0 and 'hms ' or 'hm ') .. fmt
    		end
    	end
    	local function bad_format()
    		-- For consistency with other format processing, return given format
    		-- (or cleaned format if original was not a string) if invalid.
    		return mw.text.nowiki(fmt)
    	end
    	if date.partial then
    		-- Ignore days in standard formats like 'ymd'.
    		if fmt == 'ym' or fmt == 'ymd' then
    			fmt = date.month and '%Y-%m %{era}' or '%Y %{era}'
    		elseif fmt == 'my' or fmt == 'dmy' or fmt == 'mdy' then
    			fmt = date.month and '%B %-Y %{era}' or '%-Y %{era}'
    		elseif fmt == 'y' then
    			fmt = date.month and '%-Y %{era}' or '%-Y %{era}'
    		else
    			return bad_format()
    		end
    		return strftime(date, fmt, options)
    	end
    	local function hm_fmt()
    		local plain = make_option_table(options, date.options).bydefault.am
    		return plain and '%H:%M' or '%-I:%M %p'
    	end
    	local need_time = date.hastime
    	local t = collection()
    	for item in fmt:gmatch('%S+') do
    		local f
    		if item == 'hm' then
    			f = hm_fmt()
    			need_time = false
    		elseif item == 'hms' then
    			f = '%H:%M:%S'
    			need_time = false
    		elseif item == 'ymd' then
    			f = '%Y-%m-%d %{era}'
    		elseif item == 'mdy' then
    			f = '%B %-d, %-Y %{era}'
    		elseif item == 'dmy' then
    			f = '%-d %B %-Y %{era}'
    		else
    			return bad_format()
    		end
    		t:add(f)
    	end
    	fmt = t:join(' ')
    	if need_time then
    		fmt = hm_fmt() .. ' ' .. fmt
    	end
    	return strftime(date, fmt, options)
    end
    
    local day_info = {
    	-- 0=Sun to 6=Sat
    	[0] = { 'Sun', 'Sunday' },
    	{ 'Mon', 'Monday' },
    	{ 'Tue', 'Tuesday' },
    	{ 'Wed', 'Wednesday' },
    	{ 'Thu', 'Thursday' },
    	{ 'Fri', 'Friday' },
    	{ 'Sat', 'Saturday' },
    }
    
    local month_info = {
    	-- 1=Jan to 12=Dec
    	{ 'Jan', 'January' },
    	{ 'Feb', 'February' },
    	{ 'Mar', 'March' },
    	{ 'Apr', 'April' },
    	{ 'May', 'May' },
    	{ 'Jun', 'June' },
    	{ 'Jul', 'July' },
    	{ 'Aug', 'August' },
    	{ 'Sep', 'September' },
    	{ 'Oct', 'October' },
    	{ 'Nov', 'November' },
    	{ 'Dec', 'December' },
    }
    
    local function name_to_number(text, translate)
    	if type(text) == 'string' then
    		return translate[text:lower()]
    	end
    end
    
    local function day_number(text)
    	return name_to_number(text, {
    		sun = 0, sunday = 0,
    		mon = 1, monday = 1,
    		tue = 2, tuesday = 2,
    		wed = 3, wednesday = 3,
    		thu = 4, thursday = 4,
    		fri = 5, friday = 5,
    		sat = 6, saturday = 6,
    	})
    end
    
    local function month_number(text)
    	return name_to_number(text, {
    		jan = 1, january = 1,
    		feb = 2, february = 2,
    		mar = 3, march = 3,
    		apr = 4, april = 4,
    		may = 5,
    		jun = 6, june = 6,
    		jul = 7, july = 7,
    		aug = 8, august = 8,
    		sep = 9, september = 9, sept = 9,
    		oct = 10, october = 10,
    		nov = 11, november = 11,
    		dec = 12, december = 12,
    	})
    end
    
    local function _list_text(list, fmt)
    	-- Return a list of formatted strings from a list of dates.
    	if not type(list) == 'table' then
    		error('date:list:text: need "list:text()" with a colon', 2)
    	end
    	local result = { join = _list_join }
    	for i, date in ipairs(list) do
    		result[i] = date:text(fmt)
    	end
    	return result
    end
    
    local function _date_list(date, spec)
    	-- Return a possibly empty numbered table of dates meeting the specification.
    	-- Dates in the list are in ascending order (oldest date first).
    	-- The spec should be a string of form "<count> <day> <op>"
    	-- where each item is optional and
    	--   count = number of items wanted in list
    	--   day = abbreviation or name such as Mon or Monday
    	--   op = >, >=, <, <= (default is > meaning after date)
    	-- If no count is given, the list is for the specified days in date's month.
    	-- The default day is date's day.
    	-- The spec can also be a positive or negative number:
    	--   -5 is equivalent to '5 <'
    	--   5  is equivalent to '5' which is '5 >'
    	if not is_date(date) then
    		error('date:list: need a date (use "date:list()" with a colon)', 2)
    	end
    	local list = { text = _list_text }
    	if date.partial then
    		return list
    	end
    	local count, offset, operation
    	local ops = {
    		['>='] = { before = false, include = true  },
    		['>']  = { before = false, include = false },
    		['<='] = { before = true , include = true  },
    		['<']  = { before = true , include = false },
    	}
    	if spec then
    		if type(spec) == 'number' then
    			count = floor(spec + 0.5)
    			if count < 0 then
    				count = -count
    				operation = ops['<']
    			end
    		elseif type(spec) == 'string' then
    			local num, day, op = spec:match('^%s*(%d*)%s*(%a*)%s*([<>=]*)%s*$')
    			if not num then
    				return list
    			end
    			if num ~= '' then
    				count = tonumber(num)
    			end
    			if day ~= '' then
    				local dow = day_number(day:gsub('[sS]$', ''))  -- accept plural days
    				if not dow then
    					return list
    				end
    				offset = dow - date.dow
    			end
    			operation = ops[op]
    		else
    			return list
    		end
    	end
    	offset = offset or 0
    	operation = operation or ops['>']
    	local datefrom, dayfirst, daylast
    	if operation.before then
    		if offset > 0 or (offset == 0 and not operation.include) then
    			offset = offset - 7
    		end
    		if count then
    			if count > 1 then
    				offset = offset - 7*(count - 1)
    			end
    			datefrom = date + offset
    		else
    			daylast = date.day + offset
    			dayfirst = daylast % 7
    			if dayfirst == 0 then
    				dayfirst = 7
    			end
    		end
    	else
    		if offset < 0 or (offset == 0 and not operation.include) then
    			offset = offset + 7
    		end
    		if count then
    			datefrom = date + offset
    		else
    			dayfirst = date.day + offset
    			daylast = date.monthdays
    		end
    	end
    	if not count then
    		if daylast < dayfirst then
    			return list
    		end
    		count = floor((daylast - dayfirst)/7) + 1
    		datefrom = Date(date, {day = dayfirst})
    	end
    	for i = 1, count do
    		if not datefrom then break end  -- exceeds date limits
    		list[i] = datefrom
    		datefrom = datefrom + 7
    	end
    	return list
    end
    
    -- A table to get the current date/time (UTC), but only if needed.
    local current = setmetatable({}, {
    	__index = function (self, key)
    		local d = os.date('!*t')
    		self.year = d.year
    		self.month = d.month
    		self.day = d.day
    		self.hour = d.hour
    		self.minute = d.min
    		self.second = d.sec
    		return rawget(self, key)
    	end })
    
    local function extract_date(newdate, text)
    	-- Parse the date/time in text and return n, o where
    	--   n = table of numbers wi