Module:Age: Difference between revisions

4,412 bytes added ,  2 years ago
m
29 revisions imported from wikipedia:Module:Age
(update from sandbox: implement Template:Death date and age)
m (29 revisions imported from wikipedia:Module:Age)
 
(6 intermediate revisions by one other user not shown)
Line 1:
-- Implement various "age of" and other date-related templates.
 
local mtext = {
-- Message and other text that should be localized.
-- Also need to localize text in table names in function dateDifference.
['mt-bad-param1'] = 'Invalid parameter $1',
['mt-bad-param2'] = 'Parameter $1=$2 is invalid',
['mt-bad-show'] = 'Parameter show=$1 is not supported here',
['mt-cannot-add'] = 'Cannot add "$1"',
['mt-conflicting-show'] = 'Parameter show=$1 conflicts with round=$2',
['mt-date-wrong-order'] = 'The second date must be later in time than the first date',
['mt-dd-future'] = 'Death date (first date) must not be in the future',
['mt-dd-wrong-order'] = 'Death date (first date) must be later in time than the birth date (second date)',
['mt-invalid-bd-age'] = 'Invalid birth date for calculating age',
['mt-invalid-dates-age'] = 'Invalid dates for calculating age',
['mt-invalid-end'] = 'Invalid end date in second parameter',
['mt-invalid-start'] = 'Invalid start date in first parameter',
['mt-need-jdn'] = 'Need valid Julian date number',
['mt-need-valid-bd'] = 'Need valid birth date: year, month, day',
['mt-need-valid-bd2'] = 'Need valid birth date (second date): year, month, day',
['mt-need-valid-date'] = 'Need valid date',
['mt-need-valid-dd'] = 'Need valid death date (first date): year, month, day',
['mt-need-valid-ymd'] = 'Need valid year, month, day',
['mt-need-valid-ymd-current'] = 'Need valid year|month|day or "currentdate"',
['mt-need-valid-ymd2'] = 'Second date should be year, month, day',
['mt-template-bad-name'] = 'The specified template name is not valid',
['mt-template-x'] = 'The template invoking this must have "|template=x" where x is the wanted operation',
['txt-and'] = ' and ',
['txt-or'] = ' or ',
['txt-category'] = 'Category:Age error',
['txt-comma-and'] = ', and ',
['txt-error'] = 'Error: ',
['txt-format-default'] = 'mf', -- 'df' (day first = dmy) or 'mf' (month first = mdy)
['txt-module-convertnumeric'] = 'Module:ConvertNumeric',
['txt-module-date'] = 'Module:Date',
['txt-sandbox'] = 'sandbox',
['txt-bda'] = '<span style="display:none"> (<span class="bday">$1</span>) </span>$2<span class="noprint ForceAgeToShow"> (age&nbsp;$3)</span>',
['txt-dda'] = '$2<span style="display:none">($1)</span> (aged&nbsp;$3)',
['txt-bda-disp'] = 'disp_raw', -- disp_raw → age is a number only; disp_age → age is a number and unit (normally years but months or days if very young)
['txt-dda-disp'] = 'disp_raw',
['txt-dmy'] = '%-d %B %-Y',
['txt-mdy'] = '%B %-d, %-Y',
}
 
local isWarning = {
['mt-bad-param1'] = true,
}
 
local translate, from_en, to_en, isZero
if translate then
-- Functions to translate from en to local language and reverse go here.
-- See example at [[:bn:Module:বয়স]].
else
from_en = function (text)
return text
end
isZero = function (text)
return tonumber(text) == 0
end
end
 
local _Date, _currentDate
Line 5 ⟶ 64:
-- Return objects exported from the date module or its sandbox.
if not _Date then
local sandbox = frame:getTitle():find(mtext['txt-sandbox'], 1, true) and ('/' .. mtext['txt-sandbox']) or ''
local datemod = require(mtext['Module:Datetxt-module-date'] .. sandbox)
_Datelocal realDate = datemod._Date
_currentDate = datemod._current
if to_en then
_Date = function (...)
local args = {}
for i, v in ipairs({...}) do
args[i] = to_en(v)
end
return realDate(unpack(args))
end
else
_Date = realDate
end
end
return _Date, _currentDate
Line 46 ⟶ 116:
end
return text
end
 
local function dateFormat(args)
-- Return string for wanted date format.
local default = mtext['txt-format-default']
local other = default == 'df' and 'mf' or 'df'
local wanted = stripToNil(args[other]) and other or default
return wanted == 'df' and mtext['txt-dmy'] or mtext['txt-mdy']
end
 
local function substituteParameters(text, ...)
-- Return text after substituting any given parameters for $1, $2, etc.
return mw.message.newRawMessage(text, ...):plain()
end
 
Line 55 ⟶ 138:
end
 
local function message(msg, id...)
-- Return formatted message text for an error or warning.
local function getText(msg)
return mtext[msg] or error('Bug: message "' .. tostring(msg) .. '" not defined')
end
local categories = {
error = mtext['txt-category'[[Category:Age error]]',
warning = mtext['txt-category'],
warning = '[[Category:Age error]]', -- same as error until determine whether 'Age warning' would be worthwhile
}
local a, b, k, category
local text = substituteParameters(getText(msg), ...)
if id == 'warning' then
if isWarning[msg] then
a = '<sup>[<i>'
b = '</i>]</sup>'
k = 'warning'
else
a = '<strong class="error">Error:' .. getText('txt-error')
b = '</strong>'
k = 'error'
end
if mw.title.getCurrentTitle():inNamespaces(0) then
-- Category only in namespaces: 0=article.
category = '[[' .. categories[idk] or.. 'error']]'
end
return
a ..
mw.text.nowiki(msgtext) ..
b ..
(category or '')
Line 106 ⟶ 195:
-- i == 1 for the first number which can optionally start with an uppercase letter.
number = tostring(number)
return require(mtext['Module:ConvertNumerictxt-module-convertnumeric']).spell_number(
number,
nil, -- fraction numerator
Line 123 ⟶ 212:
if mw.ustring.len(extra) > 1 then
-- Parameter "~" gives "~3" whereas "over" gives "over 3".
if extra:sub(-6, -1) ~= extra .. '&nbsp;' 'then
extra = extra .. ' '
end
end
if flagCurrent then
Line 148 ⟶ 239:
sortKey = string.format('%d', sortKey) .. string.format('%015.0f', math.floor(value * 10^(14-mag)))
end
local lhs, rhsresult
if sortable == 'sortable_table' then
lhsresult = 'data-sort-value="_SORTKEY_"|'
elseif sortable == 'sortable_debug' then
rhs = '"|'
result = '<span data-sort-value="_SORTKEY_♠"><span style="border:1px solid">_SORTKEY_♠</span></span>'
else
result = '<span data-sort-value="_SORTKEY_♠"></span>'
lhs = sortable == 'sortable_debug' and
'<span style="border:1px solid;display:inline;" class="sortkey">' or
'<span style="display:none" class="sortkey">'
rhs = '♠</span>'
end
return lhs ..(result:gsub('_SORTKEY_', sortKey .. rhs))
end
end
Line 204 ⟶ 293:
hm = { 'H', 'M', id = 'hm' },
hms = { 'H', 'M', 'S', id = 'hms' },
M = { 'M', id = 'M' },
s = { 'S', id = 's' },
d = { 'd', id = 'd' },
dh = { 'd', 'H', id = 'dh' },
Line 252 ⟶ 343:
return 'error'
end
return message('Need mt-need-valid -date')
end
local add = stripToNil(args.add)
Line 259 ⟶ 350:
date = date + item
if not date then
return message('Cannot mt-cannot-add "' .., item .. '"')
end
end
Line 272 ⟶ 363:
result = date[show]
if result == nil then
result = from_en(date:text(show))
elseif type(result) == 'boolean' then
result = result and '1' or '0'
else
result = from_en(tostring(result))
end
end
return (sortKey or '') .. makeExtra(args) .. (result or '')
end
 
local function rangeJoin(range)
-- Return text to be used between a range of ages.
return range == 'dash' and '–' or mtext['&nbsp;txt-or ']
end
 
Line 316 ⟶ 407:
local name = names[components[i]]
if name then
if type(name) == 'table' then
local plural = names.plural
if name not= mw.getContentLanguage():plural or (islist and v[2] or v, name) == 1 then
plural = ''
end
text:add(vstr .. sep .. name .. plural)
else
text:add(vstr)
Line 335 ⟶ 425:
elseif options.join == 'sep_serialcomma' and text.n > 2 then
first = ', '
last = mtext[', txt-comma-and ']
else
first = ', '
last = mtext[' txt-and ']
end
for i, v in ipairs(text) do
Line 368 ⟶ 458:
-- which have been validated.
local names = {
-- Each name is:
-- * a string if no plural form of the name is used; or
-- * a table of strings, one of which is selected using the rules at
-- https://translatewiki.net/wiki/Plural/Mediawiki_plural_rules
abbr_off = {
plural = 's',
sep = '&nbsp;',
y = {'year', 'years'},
m = {'month', 'months'},
w = {'week', 'weeks'},
d = {'day', 'days'},
H = {'hour', 'hours'},
M = {'minute', 'minutes'},
S = {'second', 'seconds'},
},
abbr_on = {
Line 389 ⟶ 482:
},
abbr_infant = { -- for {{age for infant}}
plural = 's',
sep = '&nbsp;',
y = {'yr', 'yrs'},
m = {'mo', 'mos'},
w = {'wk', 'wks'},
d = {'day', 'days'},
H = {'hr', 'hrs'},
M = {'min', 'mins'},
S = {'sec', 'secs'},
},
abbr_raw = {},
Line 478 ⟶ 570:
(textOptions.suffix or '')
end
return message('Parameter mt-bad-show=' .., show.id .. ' is not supported here')
end
 
Line 533 ⟶ 625:
end
if getopt.omitZero and i % 3 ~= 1 then -- omit zero months and days as unknown values but keep year 0 which is 1 BCE
if tonumberisZero(fields[i]) == 0 then
fields[i] = nil
getopt.partial = true
Line 552 ⟶ 644:
for i = 1, nrDates do
local index = i == 1 and 1 or 4
dates[i]local y, m, d = Date(fields[index], fields[index+1], fields[index+2])
if (m == 2 or m == '2') and (d == 29 or d == '29') then
-- Workaround error with following which attempt to use invalid date 2001-02-29.
-- {{age_ymwd|year1=2001|year2=2004|month2=2|day2=29}}
-- {{age_ymwd|year1=2001|month1=2|year2=2004|month2=1|day2=29}}
-- TODO Get rid of wantMixture because even this ugly code does not handle
-- 'Feb' or 'February' or 'feb' or 'february'.
if not ((y % 4 == 0 and y % 100 ~= 0) or y % 400 == 0) then
d = 28
end
end
dates[i] = Date(y, m, d)
end
else
Line 578 ⟶ 681:
end
if not dates[1] then
return message(getopt.missing1 or 'Need mt-need-valid year, month, day-ymd')
end
if getopt.single then
Line 584 ⟶ 687:
end
if not dates[2] then
return message(getopt.missing2 or 'Second date should be year, month, daymt-need-valid-ymd2')
end
return dates[1], dates[2]
Line 595 ⟶ 698:
local name = frame.args.template
if not name then
return message('The mt-template invoking this must have "|template=x" where -x is the wanted operation')
end
local args = frame:getParent().args
Line 692 ⟶ 795:
local spec = specs[name]
if not spec then
return message('The specified mt-template -bad-name is not valid')
end
if name == 'age_days' then
Line 756 ⟶ 859:
}
if (spec.negative or frame.args.negative) == 'error' and parms.diff.isnegative then
return message('The second date should not be before the first mt-date-wrong-order')
end
return from_en(dateDifference(parms))
end
 
Line 765 ⟶ 868:
local args = frame:getParent().args
local options = {
missing1 = 'Need mt-need-valid birth date: year, month, day-bd',
noMissing = true,
single = true,
Line 776 ⟶ 879:
local diff = Date('currentdate') - date
if diff.isnegative or diff.years > 150 then
return message('Invalid birth date for calculating mt-invalid-bd-age')
end
local disp, show = mtext['disp_raw', 'ytxt-bda-disp']
local show = 'y'
if diff.years < 2 then
disp = 'disp_age'
Line 787 ⟶ 891:
end
end
local result = substituteParameters(
local df = stripToNil(args.df) -- day first (dmy); default is month first (mdy)
mtext['txt-bda'],
local result = df and
date:text('%-d %B Y-%m-Y%d' or),
from_en(date:text(dateFormat(args))),
'%B %-d, %-Y'
from_en(dateDifference({
result = '(<span class="bday">%-Y-%m-%d</span>) </span>' .. result
result = '<span style="display:none"> ' ..
date:text(result) ..
'<span class="noprint ForceAgeToShow"> ' ..
'(age&nbsp;' ..
dateDifference({
diff = diff,
show = show,
Line 802 ⟶ 901:
disp = disp,
sep = 'sep_space',
}) ..)
)
')</span>'
local warnings = tonumber(frame.args.warnings)
if warnings and warnings > 0 then
Line 832 ⟶ 931:
end
if invalid then
result = result .. message('invalid parameter mt-bad-param1' .., invalid, 'warning')
end
end
Line 842 ⟶ 941:
local args = frame:getParent().args
local options = {
missing1 = 'Need mt-need-valid death date (first date): year, month, day-dd',
missing2 = 'Need mt-need-valid birth date (second date): year, month, day-bd2',
noMissing = true,
partial = true,
Line 853 ⟶ 952:
local diff = date1 - date2
if diff.isnegative then
return message('Death date (first date) must occur after birth date (second date)mt-dd-wrong-order')
end
local Date = getExports(frame)
local today = Date('currentdate') + 1 -- one day in future allows for timezones
if date1 > today then
return message('mt-dd-future')
end
local years
Line 863 ⟶ 967:
end
if years > 150 then
return message('Invalid mt-invalid-dates for calculating -age')
end
local fmt_date, fmt_ymd
local df = stripToNil(args.df) -- day first (dmy); default is month first (mdy)
local result
if date1.day then -- y, m, d known
fmt_date = dateFormat(args)
result = (df and
'%-dfmt_ymd %B= '%-Y-%m-%d' or
'%B %-d, %-Y') ..
'<span style="display:none">(%-Y-%m-%d)</span>'
elseif date1.month then -- y, m known; d unknown
fmt_date = '%B %-Y'
result =
fmt_ymd = '%B %-Y-%m-00' ..
'<span style="display:none">(%-Y-%m-00)</span>'
else -- y known; m, d unknown
resultfmt_date = '%-Y'
fmt_ymd = '%-Y-00-00' ..
'<span style="display:none">(%-Y-00-00)</span>'
end
local result = date1:textsubstituteParameters(result) ..
mtext['txt-dda'],
' (aged&nbsp;' ..
date1:text(fmt_ymd),
dateDifference({
from_en(date1:text(fmt_date)),
from_en(dateDifference({
diff = diff,
show = 'y',
abbr = 'abbr_off',
disp = mtext['disp_rawtxt-dda-disp'],
range = 'dash',
sep = 'sep_space',
}) ..)
)
')'
local warnings = tonumber(frame.args.warnings)
if warnings and warnings > 0 then
Line 914 ⟶ 1,015:
end
if invalid then
result = result .. message('invalid parameter mt-bad-param1' .., invalid, 'warning')
end
end
Line 940 ⟶ 1,041:
local date = Date('juliandate', args[1], args[2])
if date then
return from_en(date:text())
end
return message('Need valid Julian date numbermt-need-jdn')
end
 
Line 955 ⟶ 1,056:
return tostring(date.jd)
end
return message('Need mt-need-valid year/month/day or "currentdate"-ymd-current')
end
 
Line 974 ⟶ 1,075:
local date1 = Date(fix, 'partial', stripToNil(args[1]) or 'currentdatetime')
if not date1 then
return message('Invalid mt-invalid-start date in first parameter')
end
local date2 = Date(fix, 'partial', stripToNil(args[2]) or 'currentdatetime')
if not date2 then
return message('Invalid mt-invalid-end date in second parameter')
end
parms.diff = date2 - date1
Line 986 ⟶ 1,087:
parm = translate[parm]
if parm == nil then -- test for nil because false is a valid setting
return message('Parameter mt-bad-param2' .., argname .. '=' .., args[argname] .. ' is invalid')
end
parms[argname] = parm
Line 997 ⟶ 1,098:
if show then
if show.id ~= round then
return message('Parameter mt-conflicting-show=' .., args.show .. ' conflicts with round=' .., args.round)
end
else
Line 1,005 ⟶ 1,106:
parms.round = true
end
return from_en(dateDifference(parms))
end