Wikipedia cbk_zamwiki https://cbk-zam.wikipedia.org/wiki/El_Primero_Pagina MediaWiki 1.45.0-wmf.8 first-letter Medio Especial Discusión Usuario Discusión del usuario Wikipedia Discusión del Wikipedia File Discusión del file MediaWiki Discusión del MediaWiki Plantilla Discusión del plantilla Ayuda Discusión del ayuda Categoría Discusión del categoría TimedText TimedText talk Módulo Discusión del módulo Evento Evento discusión Villarrica 0 21927 116726 115044 2025-07-05T22:06:36Z DaniGonzdealta 15789 116726 wikitext text/x-wiki {{Infobox settlement | name = Villarrica | image_skyline = Paraguay_church.jpg | image_caption = Yvaroty, Villarrica | image_flag = Flagvillarica.png | image_seal = Escudo villarrica.png | image_map = <mapframe frameless align=center width=275 height=250 zoom=11 latitude=-25.7815 longitude=-56.4421 /> | map_caption = | pushpin_map = Paraguay | pushpin_label_position = left | pushpin_map_caption = [[Paraguay]] | settlement_type = [[Ciudad]] | subdivision_type = [[Anexo:Maga Nacion del Mundo|Nacion]] | subdivision_name = [[Paraguay]] | subdivision_type1 = Departamento | subdivision_name1 = [[Guairá]] | official_name = Villarrica del Espíritu Santo | nickname = ''Ciudad Andariega'' | established_title = Fundado | established_date = [[14 de mayo]] de [[1570]], <small>por [[Ruy Díaz de Melgarejo]]</small> | leader_title = Intendente Municipal | leader_name = Magin Benitez | government_type = | government_footnotes = | elevation_footnotes = | elevation_m = 180 | elevation_max_footnotes = | elevation_max_m = | area_rank = | area_footnotes = | area_total_km2 = 247 | population_footnotes = | population_total = 74 355 | population_as_of = 2020 | population_density_km2 = auto | population_demonym = Villarriqueño/a | population_rank = 23 | population_note = | timezone = | utc_offset = -4 | postal_code_type = Código postal | postal_code = 5000 | area_code_type = Código area | area_code = (+595) 541 | website = www.villarrica.gov.py | footnotes = }} '''Villarrica''' /viʎaˈrika/; es el capital y el ciudad mas grande del departamento de [[Guairá]], del nacion de [[Paraguay]]. El población es de 74 355 gente (2020).<ref>{{cita web|url=http://www.dgeec.gov.py/Publicaciones/Biblioteca/proyeccion%20nacional/Proyeccion%20Distrital.pdf|título=Proyección de la población por sexo y edad, según distrito. Revisión 2015|autor=DGEEC|páginas=32-37|fechaacceso=19 de noviembre de 2018}}</ref> == Referencias == <references/> == Maga Enlace Externo == * [https://web.archive.org/web/20210218121659/http://www.villarrica.gov.py/ www.villarrica.gov.py/] (en lengua español) {{commonscat|Villarrica}} [[Categoría:Paraguay]] mzocqhzlm794dkslhckzug76o6odiyu Módulo:Time ago 828 22398 116706 101325 2025-07-05T15:31:15Z Aristorkle 14080 synced with enwiki 116706 Scribunto text/plain -- Implement [[Template:Time ago]] local numberSpell, yesno -- lazy load function numberSpell(arg) numberSpell = require('Module:NumberSpell')._main return numberSpell(arg) end function yesno(arg) yesno = require('Module:Yesno') return yesno(arg) end local p = {} -- Table to convert entered text values to numeric values. local timeText = { ['seconds'] = 1, ['minutes'] = 60, ['hours'] = 3600, ['days'] = 86400, ['weeks'] = 604800, ['months'] = 2629800, -- 365.25 * 24 * 60 * 60 / 12 ['years'] = 31557600 } -- Table containing tables of possible units to use in output. local timeUnits = { [1] = { 'second', 'seconds', "second's", "seconds'" }, [60] = { 'minute', 'minutes', "minutes'", "minutes'" }, [3600] = { 'hour', 'hours', "hour's", "hours'" }, [86400] = { 'day', 'days', "day's", "days'" }, [604800] = { 'week', 'weeks', "week's", "weeks'", unit = 'w' }, [2629800] = { 'month', 'months', "month's", "months'", unit = 'm' }, [31557600] = { 'year', 'years', "year's", "years'", unit = 'y' } } function p._main( args ) -- Initialize variables local lang = mw.language.getContentLanguage() local auto_magnitude_num local min_magnitude_num local magnitude = args.magnitude local min_magnitude = args.min_magnitude local purge = args.purge -- Add a purge link if something (usually "yes") is entered into the purge parameter if purge then purge = ' <span class="plainlinks">([' .. mw.title.getCurrentTitle():fullUrl('action=purge') .. ' purge])</span>' else purge = '' end -- Check that the entered timestamp is valid. If it isn't, then give an error message. local success, inputTime = pcall( lang.formatDate, lang, 'xnU', args[1] ) if not success then return '<strong class="error">Error: first parameter cannot be parsed as a date or time.</strong>' end -- Store the difference between the current time and the inputted time, as well as its absolute value. local timeDiff = lang:formatDate( 'xnU' ) - inputTime local absTimeDiff = math.abs( timeDiff ) if magnitude then auto_magnitude_num = 0 min_magnitude_num = timeText[magnitude] else -- Calculate the appropriate unit of time if it was not specified as an argument. local autoMagnitudeData = { { factor = 2, amn = 31557600 }, { factor = 2, amn = 2629800 }, { factor = 2, amn = 86400 }, { factor = 2, amn = 3600 }, { factor = 2, amn = 60 } } for _, t in ipairs( autoMagnitudeData ) do if absTimeDiff / t.amn >= t.factor then auto_magnitude_num = t.amn break end end auto_magnitude_num = auto_magnitude_num or 1 if min_magnitude then min_magnitude_num = timeText[min_magnitude] else min_magnitude_num = -1 end end if not min_magnitude_num then -- Default to seconds if an invalid magnitude is entered. min_magnitude_num = 1 end local result_num local magnitude_num = math.max( min_magnitude_num, auto_magnitude_num ) local unit = timeUnits[magnitude_num].unit if unit and absTimeDiff >= 864000 then local Date = require('Module:Date')._Date local input = lang:formatDate('Y-m-d H:i:s', args[1]) -- Date needs a clean date input = Date(input) if input then local id if input.hour == 0 and input.minute == 0 then id = 'currentdate' else id = 'currentdatetime' end result_num = (Date(id) - input):age(unit) end end result_num = result_num or math.floor ( absTimeDiff / magnitude_num ) local punctuation_key, suffix if timeDiff >= 0 then -- Past if result_num == 1 then punctuation_key = 1 else punctuation_key = 2 end if args.ago == '' then suffix = '' else suffix = ' ' .. (args.ago or 'ago') end else -- Future if args.ago == '' then suffix = '' if result_num == 1 then punctuation_key = 1 else punctuation_key = 2 end else suffix = ' time' if result_num == 1 then punctuation_key = 3 else punctuation_key = 4 end end end local result_unit = timeUnits[ magnitude_num ][ punctuation_key ] -- Convert numerals to words if appropriate. local spell_out = args.spellout local spell_out_max = tonumber(args.spelloutmax) local result_num_text if spell_out and ( ( spell_out == 'auto' and 1 <= result_num and result_num <= 9 and result_num <= ( spell_out_max or 9 ) ) or ( yesno( spell_out ) and 1 <= result_num and result_num <= 100 and result_num <= ( spell_out_max or 100 ) ) ) then result_num_text = numberSpell( result_num ) else result_num_text = tostring( result_num ) end -- numeric or string local numeric_out = args.numeric local result = "" if numeric_out then result = tostring( result_num ) else result = result_num_text .. ' ' .. result_unit .. suffix -- Spaces for suffix have been added in earlier. end return result .. purge end function p.main( frame ) local args = require( 'Module:Arguments' ).getArgs( frame, { valueFunc = function( k, v ) if v then v = v:match( '^%s*(.-)%s*$' ) -- Trim whitespace. if k == 'ago' or v ~= '' then return v end end return nil end, wrappers = 'Template:Time ago' }) return p._main( args ) end return p owi7m6sdgrso49bzrq9mha9ire8l3cs 116710 116706 2025-07-05T16:04:42Z Aristorkle 14080 partially localized 116710 Scribunto text/plain -- Implement [[Template:Time ago]] local numberSpell, yesno -- lazy load function numberSpell(arg) numberSpell = require('Module:NumberSpell')._main return numberSpell(arg) end function yesno(arg) yesno = require('Module:Yesno') return yesno(arg) end local p = {} -- Table to convert entered text values to numeric values. local timeText = { ['segundos'] = 1, ['minutos'] = 60, ['horas'] = 3600, ['dias'] = 86400, ['semanas'] = 604800, ['meses'] = 2629800, -- 365.25 * 24 * 60 * 60 / 12 ['años'] = 31557600 } -- Table containing tables of possible units to use in output. local timeUnits = { [1] = { 'segundo', 'segundos', "segundo", "segundos" }, [60] = { 'minuto', 'minutos', "minuto", "minutos" }, [3600] = { 'hora', 'horas', "hora", "horas'" }, [86400] = { 'dia', 'dias', "dia", "dias" }, [604800] = { 'semana', 'semanas', "semana", "semanas", unit = 's' }, [2629800] = { 'mes', 'meses', "mes", "meses'", unit = 'm' }, [31557600] = { 'año', 'años', "año", "años", unit = 'a' } } function p._main( args ) -- Initialize variables local lang = mw.language.getContentLanguage() local auto_magnitude_num local min_magnitude_num local magnitude = args.magnitude local min_magnitude = args.min_magnitude local purge = args.purge -- Add a purge link if something (usually "yes") is entered into the purge parameter if purge then purge = ' <span class="plainlinks">([' .. mw.title.getCurrentTitle():fullUrl('action=purge') .. ' purge])</span>' else purge = '' end -- Check that the entered timestamp is valid. If it isn't, then give an error message. local success, inputTime = pcall( lang.formatDate, lang, 'xnU', args[1] ) if not success then return '<strong class="error">Error: first parameter cannot be parsed as a date or time.</strong>' end -- Store the difference between the current time and the inputted time, as well as its absolute value. local timeDiff = lang:formatDate( 'xnU' ) - inputTime local absTimeDiff = math.abs( timeDiff ) if magnitude then auto_magnitude_num = 0 min_magnitude_num = timeText[magnitude] else -- Calculate the appropriate unit of time if it was not specified as an argument. local autoMagnitudeData = { { factor = 2, amn = 31557600 }, { factor = 2, amn = 2629800 }, { factor = 2, amn = 86400 }, { factor = 2, amn = 3600 }, { factor = 2, amn = 60 } } for _, t in ipairs( autoMagnitudeData ) do if absTimeDiff / t.amn >= t.factor then auto_magnitude_num = t.amn break end end auto_magnitude_num = auto_magnitude_num or 1 if min_magnitude then min_magnitude_num = timeText[min_magnitude] else min_magnitude_num = -1 end end if not min_magnitude_num then -- Default to seconds if an invalid magnitude is entered. min_magnitude_num = 1 end local result_num local magnitude_num = math.max( min_magnitude_num, auto_magnitude_num ) local unit = timeUnits[magnitude_num].unit if unit and absTimeDiff >= 864000 then local Date = require('Module:Date')._Date local input = lang:formatDate('m-d-Y H:i:s', args[1]) -- Date needs a clean date input = Date(input) if input then local id if input.hour == 0 and input.minute == 0 then id = 'currentdate' else id = 'currentdatetime' end result_num = (Date(id) - input):age(unit) end end result_num = result_num or math.floor ( absTimeDiff / magnitude_num ) local punctuation_key, suffix if timeDiff >= 0 then -- Past if result_num == 1 then punctuation_key = 1 else punctuation_key = 2 end if args.ago == '' then suffix = '' else suffix = ' ' .. (args.ago or 'pasao') end else -- Future if args.ago == '' then suffix = '' if result_num == 1 then punctuation_key = 1 else punctuation_key = 2 end else suffix = ' tiempo' if result_num == 1 then punctuation_key = 3 else punctuation_key = 4 end end end local result_unit = timeUnits[ magnitude_num ][ punctuation_key ] -- Convert numerals to words if appropriate. local spell_out = args.spellout local spell_out_max = tonumber(args.spelloutmax) local result_num_text if spell_out and ( ( spell_out == 'auto' and 1 <= result_num and result_num <= 9 and result_num <= ( spell_out_max or 9 ) ) or ( yesno( spell_out ) and 1 <= result_num and result_num <= 100 and result_num <= ( spell_out_max or 100 ) ) ) then result_num_text = numberSpell( result_num ) else result_num_text = tostring( result_num ) end -- numeric or string local numeric_out = args.numeric local result = "" if numeric_out then result = tostring( result_num ) else result = result_num_text .. ' ' .. result_unit .. suffix -- Spaces for suffix have been added in earlier. end return result .. purge end function p.main( frame ) local args = require( 'Module:Arguments' ).getArgs( frame, { valueFunc = function( k, v ) if v then v = v:match( '^%s*(.-)%s*$' ) -- Trim whitespace. if k == 'ago' or v ~= '' then return v end end return nil end, wrappers = 'Template:Time ago' }) return p._main( args ) end return p pr8qaf2bydmahh4fmgrhnjhi80hdeki 116714 116710 2025-07-05T16:24:46Z Aristorkle 14080 removed repetitive units in table 116714 Scribunto text/plain -- Implement [[Template:Time ago]] local numberSpell, yesno -- lazy load function numberSpell(arg) numberSpell = require('Module:NumberSpell')._main return numberSpell(arg) end function yesno(arg) yesno = require('Module:Yesno') return yesno(arg) end local p = {} -- Table to convert entered text values to numeric values. local timeText = { ['segundos'] = 1, ['minutos'] = 60, ['horas'] = 3600, ['dias'] = 86400, ['semanas'] = 604800, ['meses'] = 2629800, -- 365.25 * 24 * 60 * 60 / 12 ['años'] = 31557600 } -- Table containing tables of possible units to use in output. local timeUnits = { [1] = { 'segundo', 'segundos' }, [60] = { 'minuto', 'minutos' }, [3600] = { 'hora', 'horas' }, [86400] = { 'dia', 'dias' }, [604800] = { 'semana', 'semanas', unit = 's' }, [2629800] = { 'mes', 'meses', unit = 'm' }, [31557600] = { 'año', 'años', unit = 'a' } } function p._main( args ) -- Initialize variables local lang = mw.language.getContentLanguage() local auto_magnitude_num local min_magnitude_num local magnitude = args.magnitude local min_magnitude = args.min_magnitude local purge = args.purge -- Add a purge link if something (usually "yes") is entered into the purge parameter if purge then purge = ' <span class="plainlinks">([' .. mw.title.getCurrentTitle():fullUrl('action=purge') .. ' purge])</span>' else purge = '' end -- Check that the entered timestamp is valid. If it isn't, then give an error message. local success, inputTime = pcall( lang.formatDate, lang, 'xnU', args[1] ) if not success then return '<strong class="error">Error: first parameter cannot be parsed as a date or time.</strong>' end -- Store the difference between the current time and the inputted time, as well as its absolute value. local timeDiff = lang:formatDate( 'xnU' ) - inputTime local absTimeDiff = math.abs( timeDiff ) if magnitude then auto_magnitude_num = 0 min_magnitude_num = timeText[magnitude] else -- Calculate the appropriate unit of time if it was not specified as an argument. local autoMagnitudeData = { { factor = 2, amn = 31557600 }, { factor = 2, amn = 2629800 }, { factor = 2, amn = 86400 }, { factor = 2, amn = 3600 }, { factor = 2, amn = 60 } } for _, t in ipairs( autoMagnitudeData ) do if absTimeDiff / t.amn >= t.factor then auto_magnitude_num = t.amn break end end auto_magnitude_num = auto_magnitude_num or 1 if min_magnitude then min_magnitude_num = timeText[min_magnitude] else min_magnitude_num = -1 end end if not min_magnitude_num then -- Default to seconds if an invalid magnitude is entered. min_magnitude_num = 1 end local result_num local magnitude_num = math.max( min_magnitude_num, auto_magnitude_num ) local unit = timeUnits[magnitude_num].unit if unit and absTimeDiff >= 864000 then local Date = require('Module:Date')._Date local input = lang:formatDate('m-d-Y H:i:s', args[1]) -- Date needs a clean date input = Date(input) if input then local id if input.hour == 0 and input.minute == 0 then id = 'currentdate' else id = 'currentdatetime' end result_num = (Date(id) - input):age(unit) end end result_num = result_num or math.floor ( absTimeDiff / magnitude_num ) local punctuation_key, suffix if timeDiff >= 0 then -- Past if result_num == 1 then punctuation_key = 1 else punctuation_key = 2 end if args.ago == '' then suffix = '' else suffix = ' ' .. (args.ago or 'pasao') end else -- Future if args.ago == '' then suffix = '' if result_num == 1 then punctuation_key = 1 else punctuation_key = 2 end else suffix = ' tiempo' if result_num == 1 then punctuation_key = 3 else punctuation_key = 4 end end end local result_unit = timeUnits[ magnitude_num ][ punctuation_key ] -- Convert numerals to words if appropriate. local spell_out = args.spellout local spell_out_max = tonumber(args.spelloutmax) local result_num_text if spell_out and ( ( spell_out == 'auto' and 1 <= result_num and result_num <= 9 and result_num <= ( spell_out_max or 9 ) ) or ( yesno( spell_out ) and 1 <= result_num and result_num <= 100 and result_num <= ( spell_out_max or 100 ) ) ) then result_num_text = numberSpell( result_num ) else result_num_text = tostring( result_num ) end -- numeric or string local numeric_out = args.numeric local result = "" if numeric_out then result = tostring( result_num ) else result = result_num_text .. ' ' .. result_unit .. suffix -- Spaces for suffix have been added in earlier. end return result .. purge end function p.main( frame ) local args = require( 'Module:Arguments' ).getArgs( frame, { valueFunc = function( k, v ) if v then v = v:match( '^%s*(.-)%s*$' ) -- Trim whitespace. if k == 'ago' or v ~= '' then return v end end return nil end, wrappers = 'Template:Time ago' }) return p._main( args ) end return p tmipkgd3cei5hchwuwpfazjhycbcoio 116715 116714 2025-07-05T16:32:18Z Aristorkle 14080 changed date format 116715 Scribunto text/plain -- Implement [[Template:Time ago]] local numberSpell, yesno -- lazy load function numberSpell(arg) numberSpell = require('Module:NumberSpell')._main return numberSpell(arg) end function yesno(arg) yesno = require('Module:Yesno') return yesno(arg) end local p = {} -- Table to convert entered text values to numeric values. local timeText = { ['segundos'] = 1, ['minutos'] = 60, ['horas'] = 3600, ['dias'] = 86400, ['semanas'] = 604800, ['meses'] = 2629800, -- 365.25 * 24 * 60 * 60 / 12 ['años'] = 31557600 } -- Table containing tables of possible units to use in output. local timeUnits = { [1] = { 'segundo', 'segundos' }, [60] = { 'minuto', 'minutos' }, [3600] = { 'hora', 'horas' }, [86400] = { 'dia', 'dias' }, [604800] = { 'semana', 'semanas', unit = 's' }, [2629800] = { 'mes', 'meses', unit = 'm' }, [31557600] = { 'año', 'años', unit = 'a' } } function p._main( args ) -- Initialize variables local lang = mw.language.getContentLanguage() local auto_magnitude_num local min_magnitude_num local magnitude = args.magnitude local min_magnitude = args.min_magnitude local purge = args.purge -- Add a purge link if something (usually "yes") is entered into the purge parameter if purge then purge = ' <span class="plainlinks">([' .. mw.title.getCurrentTitle():fullUrl('action=purge') .. ' purge])</span>' else purge = '' end -- Check that the entered timestamp is valid. If it isn't, then give an error message. local success, inputTime = pcall( lang.formatDate, lang, 'xnU', args[1] ) if not success then return '<strong class="error">Error: first parameter cannot be parsed as a date or time.</strong>' end -- Store the difference between the current time and the inputted time, as well as its absolute value. local timeDiff = lang:formatDate( 'xnU' ) - inputTime local absTimeDiff = math.abs( timeDiff ) if magnitude then auto_magnitude_num = 0 min_magnitude_num = timeText[magnitude] else -- Calculate the appropriate unit of time if it was not specified as an argument. local autoMagnitudeData = { { factor = 2, amn = 31557600 }, { factor = 2, amn = 2629800 }, { factor = 2, amn = 86400 }, { factor = 2, amn = 3600 }, { factor = 2, amn = 60 } } for _, t in ipairs( autoMagnitudeData ) do if absTimeDiff / t.amn >= t.factor then auto_magnitude_num = t.amn break end end auto_magnitude_num = auto_magnitude_num or 1 if min_magnitude then min_magnitude_num = timeText[min_magnitude] else min_magnitude_num = -1 end end if not min_magnitude_num then -- Default to seconds if an invalid magnitude is entered. min_magnitude_num = 1 end local result_num local magnitude_num = math.max( min_magnitude_num, auto_magnitude_num ) local unit = timeUnits[magnitude_num].unit if unit and absTimeDiff >= 864000 then local Date = require('Module:Date')._Date local input = lang:formatDate('Y-m-d H:i:s', args[1]) -- Date needs a clean date input = Date(input) if input then local id if input.hour == 0 and input.minute == 0 then id = 'currentdate' else id = 'currentdatetime' end result_num = (Date(id) - input):age(unit) end end result_num = result_num or math.floor ( absTimeDiff / magnitude_num ) local punctuation_key, suffix if timeDiff >= 0 then -- Past if result_num == 1 then punctuation_key = 1 else punctuation_key = 2 end if args.ago == '' then suffix = '' else suffix = ' ' .. (args.ago or 'pasao') end else -- Future if args.ago == '' then suffix = '' if result_num == 1 then punctuation_key = 1 else punctuation_key = 2 end else suffix = ' tiempo' if result_num == 1 then punctuation_key = 3 else punctuation_key = 4 end end end local result_unit = timeUnits[ magnitude_num ][ punctuation_key ] -- Convert numerals to words if appropriate. local spell_out = args.spellout local spell_out_max = tonumber(args.spelloutmax) local result_num_text if spell_out and ( ( spell_out == 'auto' and 1 <= result_num and result_num <= 9 and result_num <= ( spell_out_max or 9 ) ) or ( yesno( spell_out ) and 1 <= result_num and result_num <= 100 and result_num <= ( spell_out_max or 100 ) ) ) then result_num_text = numberSpell( result_num ) else result_num_text = tostring( result_num ) end -- numeric or string local numeric_out = args.numeric local result = "" if numeric_out then result = tostring( result_num ) else result = result_num_text .. ' ' .. result_unit .. suffix -- Spaces for suffix have been added in earlier. end return result .. purge end function p.main( frame ) local args = require( 'Module:Arguments' ).getArgs( frame, { valueFunc = function( k, v ) if v then v = v:match( '^%s*(.-)%s*$' ) -- Trim whitespace. if k == 'ago' or v ~= '' then return v end end return nil end, wrappers = 'Template:Time ago' }) return p._main( args ) end return p 6s3s28mgvlfv18d3nquhcuay1h6eu0i 116717 116715 2025-07-05T16:45:34Z Aristorkle 14080 partially localized 116717 Scribunto text/plain -- Implement [[Template:Time ago]] local numberSpell, yesno -- lazy load function numberSpell(arg) numberSpell = require('Module:NumberSpell')._main return numberSpell(arg) end function yesno(arg) yesno = require('Module:Yesno') return yesno(arg) end local p = {} -- Table to convert entered text values to numeric values. local timeText = { ['segundos'] = 1, ['minutos'] = 60, ['horas'] = 3600, ['dias'] = 86400, ['semanas'] = 604800, ['meses'] = 2629800, -- 365.25 * 24 * 60 * 60 / 12 ['años'] = 31557600 } -- Table containing tables of possible units to use in output. local timeUnits = { [1] = { 'segundo', 'segundos' }, [60] = { 'minuto', 'minutos' }, [3600] = { 'hora', 'horas' }, [86400] = { 'dia', 'dias' }, [604800] = { 'semana', 'semanas', unit = 's' }, [2629800] = { 'mes', 'meses', unit = 'm' }, [31557600] = { 'año', 'años', unit = 'a' } } function p._main( args ) -- Initialize variables local lang = mw.language.getContentLanguage() local auto_magnitude_num local min_magnitude_num local magnitude = args.magnitude local min_magnitude = args.min_magnitude local purge = args.purge -- Add a purge link if something (usually "yes") is entered into the purge parameter if purge then purge = ' <span class="plainlinks">([' .. mw.title.getCurrentTitle():fullUrl('action=purge') .. ' purge])</span>' else purge = '' end -- Check that the entered timestamp is valid. If it isn't, then give an error message. local success, inputTime = pcall( lang.formatDate, lang, 'xnU', args[1] ) if not success then return '<strong class="error">Error: first parameter cannot be parsed as a date or time.</strong>' end -- Store the difference between the current time and the inputted time, as well as its absolute value. local timeDiff = lang:formatDate( 'xnU' ) - inputTime local absTimeDiff = math.abs( timeDiff ) if magnitude then auto_magnitude_num = 0 min_magnitude_num = timeText[magnitude] else -- Calculate the appropriate unit of time if it was not specified as an argument. local autoMagnitudeData = { { factor = 2, amn = 31557600 }, { factor = 2, amn = 2629800 }, { factor = 2, amn = 86400 }, { factor = 2, amn = 3600 }, { factor = 2, amn = 60 } } for _, t in ipairs( autoMagnitudeData ) do if absTimeDiff / t.amn >= t.factor then auto_magnitude_num = t.amn break end end auto_magnitude_num = auto_magnitude_num or 1 if min_magnitude then min_magnitude_num = timeText[min_magnitude] else min_magnitude_num = -1 end end if not min_magnitude_num then -- Default to seconds if an invalid magnitude is entered. min_magnitude_num = 1 end local result_num local magnitude_num = math.max( min_magnitude_num, auto_magnitude_num ) local unit = timeUnits[magnitude_num].unit if unit and absTimeDiff >= 864000 then local Date = require('Module:Date')._Date local input = lang:formatDate('Y-m-d H:i:s', args[1]) -- Date needs a clean date input = Date(input) if input then local id if input.hour == 0 and input.minute == 0 then id = 'currentdate' else id = 'currentdatetime' end result_num = (Date(id) - input):age(unit) end end result_num = result_num or math.floor ( absTimeDiff / magnitude_num ) local punctuation_key, suffix if timeDiff >= 0 then -- Past if result_num == 1 then punctuation_key = 1 else punctuation_key = 2 end if args.ago == '' then suffix = '' else suffix = ' ' .. (args.ago or 'pasao') end else -- Future if args.ago == '' then suffix = '' if result_num == 1 then punctuation_key = 1 else punctuation_key = 2 end else suffix = ' na futuro' if result_num == 1 then punctuation_key = 3 else punctuation_key = 4 end end end local result_unit = timeUnits[ magnitude_num ][ punctuation_key ] -- Convert numerals to words if appropriate. local spell_out = args.spellout local spell_out_max = tonumber(args.spelloutmax) local result_num_text if spell_out and ( ( spell_out == 'auto' and 1 <= result_num and result_num <= 9 and result_num <= ( spell_out_max or 9 ) ) or ( yesno( spell_out ) and 1 <= result_num and result_num <= 100 and result_num <= ( spell_out_max or 100 ) ) ) then result_num_text = numberSpell( result_num ) else result_num_text = tostring( result_num ) end -- numeric or string local numeric_out = args.numeric local result = "" if numeric_out then result = tostring( result_num ) else result = result_num_text .. ' ' .. result_unit .. suffix -- Spaces for suffix have been added in earlier. end return result .. purge end function p.main( frame ) local args = require( 'Module:Arguments' ).getArgs( frame, { valueFunc = function( k, v ) if v then v = v:match( '^%s*(.-)%s*$' ) -- Trim whitespace. if k == 'ago' or v ~= '' then return v end end return nil end, wrappers = 'Template:Time ago' }) return p._main( args ) end return p 33hmm74cbikep2mqrvp1787seaqruug 116721 116717 2025-07-05T16:54:10Z Aristorkle 14080 temporary fix 116721 Scribunto text/plain -- Implement [[Template:Time ago]] local numberSpell, yesno -- lazy load function numberSpell(arg) numberSpell = require('Module:NumberSpell')._main return numberSpell(arg) end function yesno(arg) yesno = require('Module:Yesno') return yesno(arg) end local p = {} -- Table to convert entered text values to numeric values. local timeText = { ['segundos'] = 1, ['minutos'] = 60, ['horas'] = 3600, ['dias'] = 86400, ['semanas'] = 604800, ['meses'] = 2629800, -- 365.25 * 24 * 60 * 60 / 12 ['años'] = 31557600 } -- Table containing tables of possible units to use in output. local timeUnits = { [1] = { 'segundo', 'segundos' }, [60] = { 'minuto', 'minutos' }, [3600] = { 'hora', 'horas' }, [86400] = { 'dia', 'dias' }, [604800] = { 'semana', 'semanas', unit = 's' }, [2629800] = { 'mes', 'meses', unit = 'm' }, [31557600] = { 'año', 'años', unit = 'a' } } function p._main( args ) -- Initialize variables local lang = mw.language.getContentLanguage() local auto_magnitude_num local min_magnitude_num local magnitude = args.magnitude local min_magnitude = args.min_magnitude local purge = args.purge -- Add a purge link if something (usually "yes") is entered into the purge parameter if purge then purge = ' <span class="plainlinks">([' .. mw.title.getCurrentTitle():fullUrl('action=purge') .. ' purge])</span>' else purge = '' end -- Check that the entered timestamp is valid. If it isn't, then give an error message. local success, inputTime = pcall( mw.timestamp, 'unix', args[1] ) if not success then return '<strong class="error">Error: first parameter cannot be parsed as a date or time.</strong>' end -- Store the difference between the current time and the inputted time, as well as its absolute value. local timeDiff = lang:formatDate( 'xnU' ) - inputTime local absTimeDiff = math.abs( timeDiff ) if magnitude then auto_magnitude_num = 0 min_magnitude_num = timeText[magnitude] else -- Calculate the appropriate unit of time if it was not specified as an argument. local autoMagnitudeData = { { factor = 2, amn = 31557600 }, { factor = 2, amn = 2629800 }, { factor = 2, amn = 86400 }, { factor = 2, amn = 3600 }, { factor = 2, amn = 60 } } for _, t in ipairs( autoMagnitudeData ) do if absTimeDiff / t.amn >= t.factor then auto_magnitude_num = t.amn break end end auto_magnitude_num = auto_magnitude_num or 1 if min_magnitude then min_magnitude_num = timeText[min_magnitude] else min_magnitude_num = -1 end end if not min_magnitude_num then -- Default to seconds if an invalid magnitude is entered. min_magnitude_num = 1 end local result_num local magnitude_num = math.max( min_magnitude_num, auto_magnitude_num ) local unit = timeUnits[magnitude_num].unit if unit and absTimeDiff >= 864000 then local Date = require('Module:Date')._Date local input = lang:formatDate('Y-m-d H:i:s', args[1]) -- Date needs a clean date input = Date(input) if input then local id if input.hour == 0 and input.minute == 0 then id = 'currentdate' else id = 'currentdatetime' end result_num = (Date(id) - input):age(unit) end end result_num = result_num or math.floor ( absTimeDiff / magnitude_num ) local punctuation_key, suffix if timeDiff >= 0 then -- Past if result_num == 1 then punctuation_key = 1 else punctuation_key = 2 end if args.ago == '' then suffix = '' else suffix = ' ' .. (args.ago or 'pasao') end else -- Future if args.ago == '' then suffix = '' if result_num == 1 then punctuation_key = 1 else punctuation_key = 2 end else suffix = ' na futuro' if result_num == 1 then punctuation_key = 3 else punctuation_key = 4 end end end local result_unit = timeUnits[ magnitude_num ][ punctuation_key ] -- Convert numerals to words if appropriate. local spell_out = args.spellout local spell_out_max = tonumber(args.spelloutmax) local result_num_text if spell_out and ( ( spell_out == 'auto' and 1 <= result_num and result_num <= 9 and result_num <= ( spell_out_max or 9 ) ) or ( yesno( spell_out ) and 1 <= result_num and result_num <= 100 and result_num <= ( spell_out_max or 100 ) ) ) then result_num_text = numberSpell( result_num ) else result_num_text = tostring( result_num ) end -- numeric or string local numeric_out = args.numeric local result = "" if numeric_out then result = tostring( result_num ) else result = result_num_text .. ' ' .. result_unit .. suffix -- Spaces for suffix have been added in earlier. end return result .. purge end function p.main( frame ) local args = require( 'Module:Arguments' ).getArgs( frame, { valueFunc = function( k, v ) if v then v = v:match( '^%s*(.-)%s*$' ) -- Trim whitespace. if k == 'ago' or v ~= '' then return v end end return nil end, wrappers = 'Template:Time ago' }) return p._main( args ) end return p hzsc8pyikyb0wvnaoyn9iu07iwrjpmk 116722 116721 2025-07-05T16:54:53Z Aristorkle 14080 reverted 116722 Scribunto text/plain -- Implement [[Template:Time ago]] local numberSpell, yesno -- lazy load function numberSpell(arg) numberSpell = require('Module:NumberSpell')._main return numberSpell(arg) end function yesno(arg) yesno = require('Module:Yesno') return yesno(arg) end local p = {} -- Table to convert entered text values to numeric values. local timeText = { ['segundos'] = 1, ['minutos'] = 60, ['horas'] = 3600, ['dias'] = 86400, ['semanas'] = 604800, ['meses'] = 2629800, -- 365.25 * 24 * 60 * 60 / 12 ['años'] = 31557600 } -- Table containing tables of possible units to use in output. local timeUnits = { [1] = { 'segundo', 'segundos' }, [60] = { 'minuto', 'minutos' }, [3600] = { 'hora', 'horas' }, [86400] = { 'dia', 'dias' }, [604800] = { 'semana', 'semanas', unit = 's' }, [2629800] = { 'mes', 'meses', unit = 'm' }, [31557600] = { 'año', 'años', unit = 'a' } } function p._main( args ) -- Initialize variables local lang = mw.language.getContentLanguage() local auto_magnitude_num local min_magnitude_num local magnitude = args.magnitude local min_magnitude = args.min_magnitude local purge = args.purge -- Add a purge link if something (usually "yes") is entered into the purge parameter if purge then purge = ' <span class="plainlinks">([' .. mw.title.getCurrentTitle():fullUrl('action=purge') .. ' purge])</span>' else purge = '' end -- Check that the entered timestamp is valid. If it isn't, then give an error message. local success, inputTime = pcall( lang.formatDate, lang, 'xnU', args[1] ) if not success then return '<strong class="error">Error: first parameter cannot be parsed as a date or time.</strong>' end -- Store the difference between the current time and the inputted time, as well as its absolute value. local timeDiff = lang:formatDate( 'xnU' ) - inputTime local absTimeDiff = math.abs( timeDiff ) if magnitude then auto_magnitude_num = 0 min_magnitude_num = timeText[magnitude] else -- Calculate the appropriate unit of time if it was not specified as an argument. local autoMagnitudeData = { { factor = 2, amn = 31557600 }, { factor = 2, amn = 2629800 }, { factor = 2, amn = 86400 }, { factor = 2, amn = 3600 }, { factor = 2, amn = 60 } } for _, t in ipairs( autoMagnitudeData ) do if absTimeDiff / t.amn >= t.factor then auto_magnitude_num = t.amn break end end auto_magnitude_num = auto_magnitude_num or 1 if min_magnitude then min_magnitude_num = timeText[min_magnitude] else min_magnitude_num = -1 end end if not min_magnitude_num then -- Default to seconds if an invalid magnitude is entered. min_magnitude_num = 1 end local result_num local magnitude_num = math.max( min_magnitude_num, auto_magnitude_num ) local unit = timeUnits[magnitude_num].unit if unit and absTimeDiff >= 864000 then local Date = require('Module:Date')._Date local input = lang:formatDate('Y-m-d H:i:s', args[1]) -- Date needs a clean date input = Date(input) if input then local id if input.hour == 0 and input.minute == 0 then id = 'currentdate' else id = 'currentdatetime' end result_num = (Date(id) - input):age(unit) end end result_num = result_num or math.floor ( absTimeDiff / magnitude_num ) local punctuation_key, suffix if timeDiff >= 0 then -- Past if result_num == 1 then punctuation_key = 1 else punctuation_key = 2 end if args.ago == '' then suffix = '' else suffix = ' ' .. (args.ago or 'pasao') end else -- Future if args.ago == '' then suffix = '' if result_num == 1 then punctuation_key = 1 else punctuation_key = 2 end else suffix = ' na futuro' if result_num == 1 then punctuation_key = 3 else punctuation_key = 4 end end end local result_unit = timeUnits[ magnitude_num ][ punctuation_key ] -- Convert numerals to words if appropriate. local spell_out = args.spellout local spell_out_max = tonumber(args.spelloutmax) local result_num_text if spell_out and ( ( spell_out == 'auto' and 1 <= result_num and result_num <= 9 and result_num <= ( spell_out_max or 9 ) ) or ( yesno( spell_out ) and 1 <= result_num and result_num <= 100 and result_num <= ( spell_out_max or 100 ) ) ) then result_num_text = numberSpell( result_num ) else result_num_text = tostring( result_num ) end -- numeric or string local numeric_out = args.numeric local result = "" if numeric_out then result = tostring( result_num ) else result = result_num_text .. ' ' .. result_unit .. suffix -- Spaces for suffix have been added in earlier. end return result .. purge end function p.main( frame ) local args = require( 'Module:Arguments' ).getArgs( frame, { valueFunc = function( k, v ) if v then v = v:match( '^%s*(.-)%s*$' ) -- Trim whitespace. if k == 'ago' or v ~= '' then return v end end return nil end, wrappers = 'Template:Time ago' }) return p._main( args ) end return p 33hmm74cbikep2mqrvp1787seaqruug 116723 116722 2025-07-05T17:04:32Z Aristorkle 14080 changed wrappers line 183 116723 Scribunto text/plain -- Implement [[Template:Time ago]] local numberSpell, yesno -- lazy load function numberSpell(arg) numberSpell = require('Module:NumberSpell')._main return numberSpell(arg) end function yesno(arg) yesno = require('Module:Yesno') return yesno(arg) end local p = {} -- Table to convert entered text values to numeric values. local timeText = { ['segundos'] = 1, ['minutos'] = 60, ['horas'] = 3600, ['dias'] = 86400, ['semanas'] = 604800, ['meses'] = 2629800, -- 365.25 * 24 * 60 * 60 / 12 ['años'] = 31557600 } -- Table containing tables of possible units to use in output. local timeUnits = { [1] = { 'segundo', 'segundos' }, [60] = { 'minuto', 'minutos' }, [3600] = { 'hora', 'horas' }, [86400] = { 'dia', 'dias' }, [604800] = { 'semana', 'semanas', unit = 's' }, [2629800] = { 'mes', 'meses', unit = 'm' }, [31557600] = { 'año', 'años', unit = 'a' } } function p._main( args ) -- Initialize variables local lang = mw.language.getContentLanguage() local auto_magnitude_num local min_magnitude_num local magnitude = args.magnitude local min_magnitude = args.min_magnitude local purge = args.purge -- Add a purge link if something (usually "yes") is entered into the purge parameter if purge then purge = ' <span class="plainlinks">([' .. mw.title.getCurrentTitle():fullUrl('action=purge') .. ' purge])</span>' else purge = '' end -- Check that the entered timestamp is valid. If it isn't, then give an error message. local success, inputTime = pcall( lang.formatDate, lang, 'xnU', args[1] ) if not success then return '<strong class="error">Error: first parameter cannot be parsed as a date or time.</strong>' end -- Store the difference between the current time and the inputted time, as well as its absolute value. local timeDiff = lang:formatDate( 'xnU' ) - inputTime local absTimeDiff = math.abs( timeDiff ) if magnitude then auto_magnitude_num = 0 min_magnitude_num = timeText[magnitude] else -- Calculate the appropriate unit of time if it was not specified as an argument. local autoMagnitudeData = { { factor = 2, amn = 31557600 }, { factor = 2, amn = 2629800 }, { factor = 2, amn = 86400 }, { factor = 2, amn = 3600 }, { factor = 2, amn = 60 } } for _, t in ipairs( autoMagnitudeData ) do if absTimeDiff / t.amn >= t.factor then auto_magnitude_num = t.amn break end end auto_magnitude_num = auto_magnitude_num or 1 if min_magnitude then min_magnitude_num = timeText[min_magnitude] else min_magnitude_num = -1 end end if not min_magnitude_num then -- Default to seconds if an invalid magnitude is entered. min_magnitude_num = 1 end local result_num local magnitude_num = math.max( min_magnitude_num, auto_magnitude_num ) local unit = timeUnits[magnitude_num].unit if unit and absTimeDiff >= 864000 then local Date = require('Module:Date')._Date local input = lang:formatDate('Y-m-d H:i:s', args[1]) -- Date needs a clean date input = Date(input) if input then local id if input.hour == 0 and input.minute == 0 then id = 'currentdate' else id = 'currentdatetime' end result_num = (Date(id) - input):age(unit) end end result_num = result_num or math.floor ( absTimeDiff / magnitude_num ) local punctuation_key, suffix if timeDiff >= 0 then -- Past if result_num == 1 then punctuation_key = 1 else punctuation_key = 2 end if args.ago == '' then suffix = '' else suffix = ' ' .. (args.ago or 'pasao') end else -- Future if args.ago == '' then suffix = '' if result_num == 1 then punctuation_key = 1 else punctuation_key = 2 end else suffix = ' na futuro' if result_num == 1 then punctuation_key = 3 else punctuation_key = 4 end end end local result_unit = timeUnits[ magnitude_num ][ punctuation_key ] -- Convert numerals to words if appropriate. local spell_out = args.spellout local spell_out_max = tonumber(args.spelloutmax) local result_num_text if spell_out and ( ( spell_out == 'auto' and 1 <= result_num and result_num <= 9 and result_num <= ( spell_out_max or 9 ) ) or ( yesno( spell_out ) and 1 <= result_num and result_num <= 100 and result_num <= ( spell_out_max or 100 ) ) ) then result_num_text = numberSpell( result_num ) else result_num_text = tostring( result_num ) end -- numeric or string local numeric_out = args.numeric local result = "" if numeric_out then result = tostring( result_num ) else result = result_num_text .. ' ' .. result_unit .. suffix -- Spaces for suffix have been added in earlier. end return result .. purge end function p.main( frame ) local args = require( 'Module:Arguments' ).getArgs( frame, { valueFunc = function( k, v ) if v then v = v:match( '^%s*(.-)%s*$' ) -- Trim whitespace. if k == 'ago' or v ~= '' then return v end end return nil end, wrappers = 'Template:Tiempo pasao' }) return p._main( args ) end return p m6md80ofnjfkssameshf9kklr4uvk9z 116724 116723 2025-07-05T17:13:15Z Aristorkle 14080 added back time units for future tense 116724 Scribunto text/plain -- Implement [[Template:Time ago]] local numberSpell, yesno -- lazy load function numberSpell(arg) numberSpell = require('Module:NumberSpell')._main return numberSpell(arg) end function yesno(arg) yesno = require('Module:Yesno') return yesno(arg) end local p = {} -- Table to convert entered text values to numeric values. local timeText = { ['segundos'] = 1, ['minutos'] = 60, ['horas'] = 3600, ['dias'] = 86400, ['semanas'] = 604800, ['meses'] = 2629800, -- 365.25 * 24 * 60 * 60 / 12 ['años'] = 31557600 } -- Table containing tables of possible units to use in output. local timeUnits = { [1] = { 'segundo', 'segundos', 'segundo', 'segundos' }, [60] = { 'minuto', 'minutos', 'minuto', 'minutos' }, [3600] = { 'hora', 'horas', 'hora', 'horas' }, [86400] = { 'dia', 'dias', 'dia', 'dias' }, [604800] = { 'semana', 'semanas', 'semana', 'semanas', unit = 's' }, [2629800] = { 'mes', 'meses', 'mes', 'meses', unit = 'm' }, [31557600] = { 'año', 'años', 'año', 'años', unit = 'a' } } function p._main( args ) -- Initialize variables local lang = mw.language.getContentLanguage() local auto_magnitude_num local min_magnitude_num local magnitude = args.magnitude local min_magnitude = args.min_magnitude local purge = args.purge -- Add a purge link if something (usually "yes") is entered into the purge parameter if purge then purge = ' <span class="plainlinks">([' .. mw.title.getCurrentTitle():fullUrl('action=purge') .. ' purge])</span>' else purge = '' end -- Check that the entered timestamp is valid. If it isn't, then give an error message. local success, inputTime = pcall( lang.formatDate, lang, 'xnU', args[1] ) if not success then return '<strong class="error">Error: first parameter cannot be parsed as a date or time.</strong>' end -- Store the difference between the current time and the inputted time, as well as its absolute value. local timeDiff = lang:formatDate( 'xnU' ) - inputTime local absTimeDiff = math.abs( timeDiff ) if magnitude then auto_magnitude_num = 0 min_magnitude_num = timeText[magnitude] else -- Calculate the appropriate unit of time if it was not specified as an argument. local autoMagnitudeData = { { factor = 2, amn = 31557600 }, { factor = 2, amn = 2629800 }, { factor = 2, amn = 86400 }, { factor = 2, amn = 3600 }, { factor = 2, amn = 60 } } for _, t in ipairs( autoMagnitudeData ) do if absTimeDiff / t.amn >= t.factor then auto_magnitude_num = t.amn break end end auto_magnitude_num = auto_magnitude_num or 1 if min_magnitude then min_magnitude_num = timeText[min_magnitude] else min_magnitude_num = -1 end end if not min_magnitude_num then -- Default to seconds if an invalid magnitude is entered. min_magnitude_num = 1 end local result_num local magnitude_num = math.max( min_magnitude_num, auto_magnitude_num ) local unit = timeUnits[magnitude_num].unit if unit and absTimeDiff >= 864000 then local Date = require('Module:Date')._Date local input = lang:formatDate('Y-m-d H:i:s', args[1]) -- Date needs a clean date input = Date(input) if input then local id if input.hour == 0 and input.minute == 0 then id = 'currentdate' else id = 'currentdatetime' end result_num = (Date(id) - input):age(unit) end end result_num = result_num or math.floor ( absTimeDiff / magnitude_num ) local punctuation_key, suffix if timeDiff >= 0 then -- Past if result_num == 1 then punctuation_key = 1 else punctuation_key = 2 end if args.ago == '' then suffix = '' else suffix = ' ' .. (args.ago or 'pasao') end else -- Future if args.ago == '' then suffix = '' if result_num == 1 then punctuation_key = 1 else punctuation_key = 2 end else suffix = ' na futuro' if result_num == 1 then punctuation_key = 3 else punctuation_key = 4 end end end local result_unit = timeUnits[ magnitude_num ][ punctuation_key ] -- Convert numerals to words if appropriate. local spell_out = args.spellout local spell_out_max = tonumber(args.spelloutmax) local result_num_text if spell_out and ( ( spell_out == 'auto' and 1 <= result_num and result_num <= 9 and result_num <= ( spell_out_max or 9 ) ) or ( yesno( spell_out ) and 1 <= result_num and result_num <= 100 and result_num <= ( spell_out_max or 100 ) ) ) then result_num_text = numberSpell( result_num ) else result_num_text = tostring( result_num ) end -- numeric or string local numeric_out = args.numeric local result = "" if numeric_out then result = tostring( result_num ) else result = result_num_text .. ' ' .. result_unit .. suffix -- Spaces for suffix have been added in earlier. end return result .. purge end function p.main( frame ) local args = require( 'Module:Arguments' ).getArgs( frame, { valueFunc = function( k, v ) if v then v = v:match( '^%s*(.-)%s*$' ) -- Trim whitespace. if k == 'ago' or v ~= '' then return v end end return nil end, wrappers = 'Template:Tiempo pasao' }) return p._main( args ) end return p 4nq75j4fap1ctwpdaedze6lznnwtkz0 116725 116724 2025-07-05T17:31:17Z Aristorkle 14080 fixed future tense to reduce repetitiveness 116725 Scribunto text/plain -- Implement [[Template:Time ago]] local numberSpell, yesno -- lazy load function numberSpell(arg) numberSpell = require('Module:NumberSpell')._main return numberSpell(arg) end function yesno(arg) yesno = require('Module:Yesno') return yesno(arg) end local p = {} -- Table to convert entered text values to numeric values. local timeText = { ['segundos'] = 1, ['minutos'] = 60, ['horas'] = 3600, ['dias'] = 86400, ['semanas'] = 604800, ['meses'] = 2629800, -- 365.25 * 24 * 60 * 60 / 12 ['años'] = 31557600 } -- Table containing tables of possible units to use in output. local timeUnits = { [1] = { 'segundo', 'segundos' }, [60] = { 'minuto', 'minutos' }, [3600] = { 'hora', 'horas' }, [86400] = { 'dia', 'dias' }, [604800] = { 'semana', 'semanas', unit = 's' }, [2629800] = { 'mes', 'meses', unit = 'm' }, [31557600] = { 'año', 'años', unit = 'a' } } function p._main( args ) -- Initialize variables local lang = mw.language.getContentLanguage() local auto_magnitude_num local min_magnitude_num local magnitude = args.magnitude local min_magnitude = args.min_magnitude local purge = args.purge -- Add a purge link if something (usually "yes") is entered into the purge parameter if purge then purge = ' <span class="plainlinks">([' .. mw.title.getCurrentTitle():fullUrl('action=purge') .. ' purge])</span>' else purge = '' end -- Check that the entered timestamp is valid. If it isn't, then give an error message. local success, inputTime = pcall( lang.formatDate, lang, 'xnU', args[1] ) if not success then return '<strong class="error">Error: first parameter cannot be parsed as a date or time.</strong>' end -- Store the difference between the current time and the inputted time, as well as its absolute value. local timeDiff = lang:formatDate( 'xnU' ) - inputTime local absTimeDiff = math.abs( timeDiff ) if magnitude then auto_magnitude_num = 0 min_magnitude_num = timeText[magnitude] else -- Calculate the appropriate unit of time if it was not specified as an argument. local autoMagnitudeData = { { factor = 2, amn = 31557600 }, { factor = 2, amn = 2629800 }, { factor = 2, amn = 86400 }, { factor = 2, amn = 3600 }, { factor = 2, amn = 60 } } for _, t in ipairs( autoMagnitudeData ) do if absTimeDiff / t.amn >= t.factor then auto_magnitude_num = t.amn break end end auto_magnitude_num = auto_magnitude_num or 1 if min_magnitude then min_magnitude_num = timeText[min_magnitude] else min_magnitude_num = -1 end end if not min_magnitude_num then -- Default to seconds if an invalid magnitude is entered. min_magnitude_num = 1 end local result_num local magnitude_num = math.max( min_magnitude_num, auto_magnitude_num ) local unit = timeUnits[magnitude_num].unit if unit and absTimeDiff >= 864000 then local Date = require('Module:Date')._Date local input = lang:formatDate('Y-m-d H:i:s', args[1]) -- Date needs a clean date input = Date(input) if input then local id if input.hour == 0 and input.minute == 0 then id = 'currentdate' else id = 'currentdatetime' end result_num = (Date(id) - input):age(unit) end end result_num = result_num or math.floor ( absTimeDiff / magnitude_num ) local punctuation_key, suffix if timeDiff >= 0 then -- Past if result_num == 1 then punctuation_key = 1 else punctuation_key = 2 end if args.ago == '' then suffix = '' else suffix = ' ' .. (args.ago or 'pasao') end else -- Future if args.ago == '' then suffix = '' if result_num == 1 then punctuation_key = 1 else punctuation_key = 2 end else suffix = ' na futuro' if result_num == 1 then punctuation_key = 1 else punctuation_key = 2 end end end local result_unit = timeUnits[ magnitude_num ][ punctuation_key ] -- Convert numerals to words if appropriate. local spell_out = args.spellout local spell_out_max = tonumber(args.spelloutmax) local result_num_text if spell_out and ( ( spell_out == 'auto' and 1 <= result_num and result_num <= 9 and result_num <= ( spell_out_max or 9 ) ) or ( yesno( spell_out ) and 1 <= result_num and result_num <= 100 and result_num <= ( spell_out_max or 100 ) ) ) then result_num_text = numberSpell( result_num ) else result_num_text = tostring( result_num ) end -- numeric or string local numeric_out = args.numeric local result = "" if numeric_out then result = tostring( result_num ) else result = result_num_text .. ' ' .. result_unit .. suffix -- Spaces for suffix have been added in earlier. end return result .. purge end function p.main( frame ) local args = require( 'Module:Arguments' ).getArgs( frame, { valueFunc = function( k, v ) if v then v = v:match( '^%s*(.-)%s*$' ) -- Trim whitespace. if k == 'ago' or v ~= '' then return v end end return nil end, wrappers = 'Template:Tiempo pasao' }) return p._main( args ) end return p 5x6d6tp9mjf8gbsumnla7o5v6g2uo54 Módulo:NumberSpell 828 22399 116713 101326 2025-07-05T16:22:18Z Aristorkle 14080 localized 116713 Scribunto text/plain -- This module converts a number into its written English form. -- For example, "2" becomes "two", and "79" becomes "seventy-nine". local getArgs = require('Module:Arguments').getArgs local p = {} local max = 100 -- The maximum number that can be parsed. local ones = { [0] = 'cero', [1] = 'uno', [2] = 'dos', [3] = 'tres', [4] = 'cuatro', [5] = 'cinco', [6] = 'seis', [7] = 'siete', [8] = 'ocho', [9] = 'nueve' } local specials = { [10] = 'diez', [11] = 'once', [12] = 'doce', [13] = 'trece', [14] = 'catorce', [15] = 'cince', [20] = 'veinte', [30] = 'treinta', [40] = 'cuarenta', [50] = 'cincuenta', [60] = 'sesenta', [70] = 'setenta', [80] = 'ochenta', [90] = 'noventa', [100] = 'ciento' } local formatRules = { {num = 90, rule = 'noventa y %s'}, {num = 80, rule = 'ochenta y %s'}, {num = 70, rule = 'setenta y %s'}, {num = 60, rule = 'sesenta y %s'}, {num = 50, rule = 'cincuenta y %s'}, {num = 40, rule = 'cuarenta y %s'}, {num = 30, rule = 'treinta y %s'}, {num = 20, rule = 'veinti%s'}, {num = 10, rule = 'dieci%s'} } function p.main(frame) local args = getArgs(frame) local num = tonumber(args[1]) local success, result = pcall(p._main, num) if success then return result else return string.format('<strong class="error">Error: %s</strong>', result) -- "result" is the error message. end return p._main(num) end function p._main(num) if type(num) ~= 'number' or math.floor(num) ~= num or num < 0 or num > max then error('input must be an integer between 0 and ' .. tostring(max), 2) end -- Check for numbers from 0 to 9. local onesVal = ones[num] if onesVal then return onesVal end -- Check for special numbers. local specialVal = specials[num] if specialVal then return specialVal end -- Construct the number from its format rule. onesVal = ones[num % 10] if not onesVal then error('Unexpected error parsing input ' .. tostring(num)) end for i, t in ipairs(formatRules) do if num >= t.num then return string.format(t.rule, onesVal) end end error('No format rule found for input ' .. tostring(num)) end return p s66dyxp9xqrcb1qvvogkipa7atr41ll Módulo:ConvertNumeric 828 23146 116720 103478 2025-07-05T16:48:55Z Aristorkle 14080 synced with enwiki 116720 Scribunto text/plain -- Module for converting between different representations of numbers. See talk page for user documentation. -- For unit tests see: [[Module:ConvertNumeric/testcases]] -- When editing, preview with: [[Module_talk:ConvertNumeric/testcases]] -- First, edit [[Module:ConvertNumeric/sandbox]], then preview with [[Module_talk:ConvertNumeric/sandbox/testcases]] require('strict') local ones_position = { [0] = 'zero', [1] = 'one', [2] = 'two', [3] = 'three', [4] = 'four', [5] = 'five', [6] = 'six', [7] = 'seven', [8] = 'eight', [9] = 'nine', [10] = 'ten', [11] = 'eleven', [12] = 'twelve', [13] = 'thirteen', [14] = 'fourteen', [15] = 'fifteen', [16] = 'sixteen', [17] = 'seventeen', [18] = 'eighteen', [19] = 'nineteen' } local ones_position_ord = { [0] = 'zeroth', [1] = 'first', [2] = 'second', [3] = 'third', [4] = 'fourth', [5] = 'fifth', [6] = 'sixth', [7] = 'seventh', [8] = 'eighth', [9] = 'ninth', [10] = 'tenth', [11] = 'eleventh', [12] = 'twelfth', [13] = 'thirteenth', [14] = 'fourteenth', [15] = 'fifteenth', [16] = 'sixteenth', [17] = 'seventeenth', [18] = 'eighteenth', [19] = 'nineteenth' } local ones_position_plural = { [0] = 'zeros', [1] = 'ones', [2] = 'twos', [3] = 'threes', [4] = 'fours', [5] = 'fives', [6] = 'sixes', [7] = 'sevens', [8] = 'eights', [9] = 'nines', [10] = 'tens', [11] = 'elevens', [12] = 'twelves', [13] = 'thirteens', [14] = 'fourteens', [15] = 'fifteens', [16] = 'sixteens', [17] = 'seventeens', [18] = 'eighteens', [19] = 'nineteens' } local tens_position = { [2] = 'twenty', [3] = 'thirty', [4] = 'forty', [5] = 'fifty', [6] = 'sixty', [7] = 'seventy', [8] = 'eighty', [9] = 'ninety' } local tens_position_ord = { [2] = 'twentieth', [3] = 'thirtieth', [4] = 'fortieth', [5] = 'fiftieth', [6] = 'sixtieth', [7] = 'seventieth', [8] = 'eightieth', [9] = 'ninetieth' } local tens_position_plural = { [2] = 'twenties', [3] = 'thirties', [4] = 'forties', [5] = 'fifties', [6] = 'sixties', [7] = 'seventies', [8] = 'eighties', [9] = 'nineties' } local groups = { [1] = 'thousand', [2] = 'million', [3] = 'billion', [4] = 'trillion', [5] = 'quadrillion', [6] = 'quintillion', [7] = 'sextillion', [8] = 'septillion', [9] = 'octillion', [10] = 'nonillion', [11] = 'decillion', [12] = 'undecillion', [13] = 'duodecillion', [14] = 'tredecillion', [15] = 'quattuordecillion', [16] = 'quindecillion', [17] = 'sexdecillion', [18] = 'septendecillion', [19] = 'octodecillion', [20] = 'novemdecillion', [21] = 'vigintillion', [22] = 'unvigintillion', [23] = 'duovigintillion', [24] = 'tresvigintillion', [25] = 'quattuorvigintillion', [26] = 'quinquavigintillion', [27] = 'sesvigintillion', [28] = 'septemvigintillion', [29] = 'octovigintillion', [30] = 'novemvigintillion', [31] = 'trigintillion', [32] = 'untrigintillion', [33] = 'duotrigintillion', [34] = 'trestrigintillion', [35] = 'quattuortrigintillion', [36] = 'quinquatrigintillion', [37] = 'sestrigintillion', [38] = 'septentrigintillion', [39] = 'octotrigintillion', [40] = 'noventrigintillion', [41] = 'quadragintillion', [51] = 'quinquagintillion', [61] = 'sexagintillion', [71] = 'septuagintillion', [81] = 'octogintillion', [91] = 'nonagintillion', [101] = 'centillion', [102] = 'uncentillion', [103] = 'duocentillion', [104] = 'trescentillion', [111] = 'decicentillion', [112] = 'undecicentillion', [121] = 'viginticentillion', [122] = 'unviginticentillion', [131] = 'trigintacentillion', [141] = 'quadragintacentillion', [151] = 'quinquagintacentillion', [161] = 'sexagintacentillion', [171] = 'septuagintacentillion', [181] = 'octogintacentillion', [191] = 'nonagintacentillion', [201] = 'ducentillion', [301] = 'trecentillion', [401] = 'quadringentillion', [501] = 'quingentillion', [601] = 'sescentillion', [701] = 'septingentillion', [801] = 'octingentillion', [901] = 'nongentillion', [1001] = 'millinillion', } local roman_numerals = { I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000 } local engord_tens_end = { ['twentieth'] = 20, ['thirtieth'] = 30, ['fortieth'] = 40, ['fiftieth'] = 50, ['sixtieth'] = 60, ['seventieth'] = 70, ['eightieth'] = 80, ['ninetieth'] = 90, } local eng_tens_cont = { ['twenty'] = 20, ['thirty'] = 30, ['forty'] = 40, ['fifty'] = 50, ['sixty'] = 60, ['seventy'] = 70, ['eighty'] = 80, ['ninety'] = 90, } -- Converts a given valid roman numeral (and some invalid roman numerals) to a number. Returns { -1, errorstring } on error. local function roman_to_numeral(roman) if type(roman) ~= "string" then return -1, "roman numeral not a string" end local rev = roman:reverse() local raising = true local last = 0 local result = 0 for i = 1, #rev do local c = rev:sub(i, i) local next = roman_numerals[c] if next == nil then return -1, "roman numeral contains illegal character " .. c end if next > last then result = result + next raising = true elseif next < last then result = result - next raising = false elseif raising then result = result + next else result = result - next end last = next end return result end -- Converts a given integer between 0 and 100 to English text (e.g. 47 -> forty-seven). local function numeral_to_english_less_100(num, ordinal, plural, zero) local terminal_ones, terminal_tens if ordinal then terminal_ones = ones_position_ord terminal_tens = tens_position_ord elseif plural then terminal_ones = ones_position_plural terminal_tens = tens_position_plural else terminal_ones = ones_position terminal_tens = tens_position end if num == 0 and zero ~= nil then return zero elseif num < 20 then return terminal_ones[num] elseif num % 10 == 0 then return terminal_tens[num / 10] else return tens_position[math.floor(num / 10)] .. '-' .. terminal_ones[num % 10] end end local function standard_suffix(ordinal, plural) if ordinal then return 'th' end if plural then return 's' end return '' end -- Converts a given integer (in string form) between 0 and 1000 to English text (e.g. 47 -> forty-seven). local function numeral_to_english_less_1000(num, use_and, ordinal, plural, zero) num = tonumber(num) if num < 100 then return numeral_to_english_less_100(num, ordinal, plural, zero) elseif num % 100 == 0 then return ones_position[num/100] .. ' hundred' .. standard_suffix(ordinal, plural) else return ones_position[math.floor(num/100)] .. ' hundred ' .. (use_and and 'and ' or '') .. numeral_to_english_less_100(num % 100, ordinal, plural, zero) end end -- Converts an ordinal in English text from 'zeroth' to 'ninety-ninth' inclusive to a number [0–99], else -1. local function english_to_ordinal(english) local eng = string.lower(english or '') local engord_lt20 = {} -- ones_position_ord{} keys & values swapped for k, v in pairs( ones_position_ord ) do engord_lt20[v] = k end if engord_lt20[eng] then return engord_lt20[eng] -- e.g. first -> 1 elseif engord_tens_end[eng] then return engord_tens_end[eng] -- e.g. ninetieth -> 90 else local tens, ones = string.match(eng, '^([a-z]+)[%s%-]+([a-z]+)$') if tens and ones then local tens_cont = eng_tens_cont[tens] local ones_end = engord_lt20[ones] if tens_cont and ones_end then return tens_cont + ones_end -- e.g. ninety-ninth -> 99 end end end return -1 -- Failed end -- Converts a number in English text from 'zero' to 'ninety-nine' inclusive to a number [0–99], else -1. local function english_to_numeral(english) local eng = string.lower(english or '') local eng_lt20 = { ['single'] = 1 } -- ones_position{} keys & values swapped for k, v in pairs( ones_position ) do eng_lt20[v] = k end if eng_lt20[eng] then return eng_lt20[eng] -- e.g. one -> 1 elseif eng_tens_cont[eng] then return eng_tens_cont[eng] -- e.g. ninety -> 90 else local tens, ones = string.match(eng, '^([a-z]+)[%s%-]+([a-z]+)$') if tens and ones then local tens_cont = eng_tens_cont[tens] local ones_end = eng_lt20[ones] if tens_cont and ones_end then return tens_cont + ones_end -- e.g. ninety-nine -> 99 end end end return -1 -- Failed end -- Converts a number expressed as a string in scientific notation to a string in standard decimal notation -- e.g. 1.23E5 -> 123000, 1.23E-5 = .0000123. Conversion is exact, no rounding is performed. local function scientific_notation_to_decimal(num) local exponent, subs = num:gsub("^%-?%d*%.?%d*%-?[Ee]([+%-]?%d+)$", "%1") if subs == 0 then return num end -- Input not in scientific notation, just return unmodified exponent = tonumber(exponent) local negative = num:find("^%-") local _, decimal_pos = num:find("%.") -- Mantissa will consist of all decimal digits with no decimal point local mantissa = num:gsub("^%-?(%d*)%.?(%d*)%-?[Ee][+%-]?%d+$", "%1%2") if negative and decimal_pos then decimal_pos = decimal_pos - 1 end if not decimal_pos then decimal_pos = #mantissa + 1 end -- Remove leading zeros unless decimal point is in first position while decimal_pos > 1 and mantissa:sub(1,1) == '0' do mantissa = mantissa:sub(2) decimal_pos = decimal_pos - 1 end -- Shift decimal point right for exponent > 0 while exponent > 0 do decimal_pos = decimal_pos + 1 exponent = exponent - 1 if decimal_pos > #mantissa + 1 then mantissa = mantissa .. '0' end -- Remove leading zeros unless decimal point is in first position while decimal_pos > 1 and mantissa:sub(1,1) == '0' do mantissa = mantissa:sub(2) decimal_pos = decimal_pos - 1 end end -- Shift decimal point left for exponent < 0 while exponent < 0 do if decimal_pos == 1 then mantissa = '0' .. mantissa else decimal_pos = decimal_pos - 1 end exponent = exponent + 1 end -- Insert decimal point in correct position and return return (negative and '-' or '') .. mantissa:sub(1, decimal_pos - 1) .. '.' .. mantissa:sub(decimal_pos) end -- Rounds a number to the nearest integer (NOT USED) local function round_num(x) if x%1 >= 0.5 then return math.ceil(x) else return math.floor(x) end end -- Rounds a number to the nearest two-word number (round = up, down, or "on" for round to nearest). -- Numbers with two digits before the decimal will be rounded to an integer as specified by round. -- Larger numbers will be rounded to a number with only one nonzero digit in front and all other digits zero. -- Negative sign is preserved and does not count towards word limit. local function round_for_english(num, round) -- If an integer with at most two digits, just return if num:find("^%-?%d?%d%.?$") then return num end local negative = num:find("^%-") if negative then -- We're rounding magnitude so flip it if round == 'up' then round = 'down' elseif round == 'down' then round = 'up' end end -- If at most two digits before decimal, round to integer and return local _, _, small_int, trailing_digits, round_digit = num:find("^%-?(%d?%d?)%.((%d)%d*)$") if small_int then if small_int == '' then small_int = '0' end if (round == 'up' and trailing_digits:find('[1-9]')) or (round == 'on' and tonumber(round_digit) >= 5) then small_int = tostring(tonumber(small_int) + 1) end return (negative and '-' or '') .. small_int end -- When rounding up, any number with > 1 nonzero digit will round up (e.g. 1000000.001 rounds up to 2000000) local nonzero_digits = 0 for digit in num:gfind("[1-9]") do nonzero_digits = nonzero_digits + 1 end num = num:gsub("%.%d*$", "") -- Remove decimal part -- Second digit used to determine which way to round lead digit local _, _, lead_digit, round_digit, round_digit_2, rest = num:find("^%-?(%d)(%d)(%d)(%d*)$") if tonumber(lead_digit .. round_digit) < 20 and (1 + #rest) % 3 == 0 then -- In English numbers < 20 are one word so put 2 digits in lead and round based on 3rd lead_digit = lead_digit .. round_digit round_digit = round_digit_2 else rest = round_digit_2 .. rest end if (round == 'up' and nonzero_digits > 1) or (round == 'on' and tonumber(round_digit) >= 5) then lead_digit = tostring(tonumber(lead_digit) + 1) end -- All digits but lead digit will turn to zero rest = rest:gsub("%d", "0") return (negative and '-' or '') .. lead_digit .. '0' .. rest end local denominators = { [2] = { 'half', plural = 'halves' }, [3] = { 'third' }, [4] = { 'quarter', us = 'fourth' }, [5] = { 'fifth' }, [6] = { 'sixth' }, [8] = { 'eighth' }, [9] = { 'ninth' }, [10] = { 'tenth' }, [16] = { 'sixteenth' }, } -- Return status, fraction where: -- status is a string: -- "finished" if there is a fraction with no whole number; -- "ok" if fraction is empty or valid; -- "unsupported" if bad fraction; -- fraction is a string giving (numerator / denominator) as English text, or is "". -- Only unsigned fractions with a very limited range of values are supported, -- except that if whole is empty, the numerator can use "-" to indicate negative. -- whole (string or nil): nil or "" if no number before the fraction -- numerator (string or nil): numerator, if any (default = 1 if a denominator is given) -- denominator (string or nil): denominator, if any -- sp_us (boolean): true if sp=us -- negative_word (string): word to use for negative sign, if whole is empty -- use_one (boolean): false: 2+1/2 → "two and a half"; true: "two and one-half" local function fraction_to_english(whole, numerator, denominator, sp_us, negative_word, use_one) if numerator or denominator then local finished = (whole == nil or whole == '') local sign = '' if numerator then if finished and numerator:sub(1, 1) == '-' then numerator = numerator:sub(2) sign = negative_word .. ' ' end else numerator = '1' end if not numerator:match('^%d+$') or not denominator or not denominator:match('^%d+$') then return 'unsupported', '' end numerator = tonumber(numerator) denominator = tonumber(denominator) local dendata = denominators[denominator] if not (dendata and 1 <= numerator and numerator <= 99) then return 'unsupported', '' end local numstr, denstr local sep = '-' if numerator == 1 then denstr = sp_us and dendata.us or dendata[1] if finished or use_one then numstr = 'one' elseif denstr:match('^[aeiou]') then numstr = 'an' sep = ' ' else numstr = 'a' sep = ' ' end else numstr = numeral_to_english_less_100(numerator) denstr = dendata.plural if not denstr then denstr = (sp_us and dendata.us or dendata[1]) .. 's' end end if finished then return 'finished', sign .. numstr .. sep .. denstr end return 'ok', ' and ' .. numstr .. sep .. denstr end return 'ok', '' end -- Takes a decimal number and converts it to English text. -- Return nil if a fraction cannot be converted (only some numbers are supported for fractions). -- num (string or nil): the number to convert. -- Can be an arbitrarily large decimal, such as "-123456789123456789.345", and -- can use scientific notation (e.g. "1.23E5"). -- May fail for very large numbers not listed in "groups" such as "1E4000". -- num is nil if there is no whole number before a fraction. -- numerator (string or nil): numerator of fraction (nil if no fraction) -- denominator (string or nil): denominator of fraction (nil if no fraction) -- capitalize (boolean): whether to capitalize the result (e.g. 'One' instead of 'one') -- use_and (boolean): whether to use the word 'and' between tens/ones place and higher places -- hyphenate (boolean): whether to hyphenate all words in the result, useful as an adjective -- ordinal (boolean): whether to produce an ordinal (e.g. 'first' instead of 'one') -- plural (boolean): whether to pluralize the resulting number -- links: nil: do not add any links; 'on': link "billion" and larger to Orders of magnitude article; -- any other text: list of numbers to link (e.g. "billion,quadrillion") -- negative_word: word to use for negative sign (typically 'negative' or 'minus'; nil to use default) -- round: nil or '': no rounding; 'on': round to nearest two-word number; 'up'/'down': round up/down to two-word number -- zero: word to use for value '0' (nil to use default) -- use_one (boolean): false: 2+1/2 → "two and a half"; true: "two and one-half" local function _numeral_to_english(num, numerator, denominator, capitalize, use_and, hyphenate, ordinal, plural, links, negative_word, round, zero, use_one) if not negative_word then if use_and then -- TODO Should 'minus' be used when do not have sp=us? -- If so, need to update testcases, and need to fix "minus zero". -- negative_word = 'minus' negative_word = 'negative' else negative_word = 'negative' end end local status, fraction_text = fraction_to_english(num, numerator, denominator, not use_and, negative_word, use_one) if status == 'unsupported' then return nil end if status == 'finished' then -- Input is a fraction with no whole number. -- Hack to avoid executing stuff that depends on num being a number. local s = fraction_text if hyphenate then s = s:gsub("%s", "-") end if capitalize then s = s:gsub("^%l", string.upper) end return s end num = scientific_notation_to_decimal(num) if round and round ~= '' then if round ~= 'on' and round ~= 'up' and round ~= 'down' then error("Invalid rounding mode") end num = round_for_english(num, round) end -- Separate into negative sign, num (digits before decimal), decimal_places (digits after decimal) local MINUS = '−' -- Unicode U+2212 MINUS SIGN (may be in values from [[Module:Convert]]) if num:sub(1, #MINUS) == MINUS then num = '-' .. num:sub(#MINUS + 1) -- replace MINUS with '-' elseif num:sub(1, 1) == '+' then num = num:sub(2) -- ignore any '+' end local negative = num:find("^%-") local decimal_places, subs = num:gsub("^%-?%d*%.(%d+)$", "%1") if subs == 0 then decimal_places = nil end num, subs = num:gsub("^%-?(%d*)%.?%d*$", "%1") if num == '' and decimal_places then num = '0' end if subs == 0 or num == '' then error("Invalid decimal numeral") end -- For each group of 3 digits except the last one, print with appropriate group name (e.g. million) local s = '' while #num > 3 do if s ~= '' then s = s .. ' ' end local group_num = math.floor((#num - 1) / 3) local group = groups[group_num] local group_digits = #num - group_num*3 s = s .. numeral_to_english_less_1000(num:sub(1, group_digits), false, false, false, zero) .. ' ' if links and (((links == 'on' and group_num >= 3) or links:find(group)) and group_num <= 13) then s = s .. '[[Orders_of_magnitude_(numbers)#10' .. group_num*3 .. '|' .. group .. ']]' else s = s .. group end num = num:sub(1 + group_digits) num = num:gsub("^0*", "") -- Trim leading zeros end -- Handle final three digits of integer part if s ~= '' and num ~= '' then if #num <= 2 and use_and then s = s .. ' and ' else s = s .. ' ' end end if s == '' or num ~= '' then s = s .. numeral_to_english_less_1000(num, use_and, ordinal, plural, zero) elseif ordinal or plural then -- Round numbers like "one million" take standard suffixes for ordinal/plural s = s .. standard_suffix(ordinal, plural) end -- For decimal places (if any) output "point" followed by spelling out digit by digit if decimal_places then s = s .. ' point' for i = 1, #decimal_places do s = s .. ' ' .. ones_position[tonumber(decimal_places:sub(i,i))] end end s = s:gsub("^%s*(.-)%s*$", "%1") -- Trim whitespace if ordinal and plural then s = s .. 's' end -- s suffix works for all ordinals if negative and s ~= zero then s = negative_word .. ' ' .. s end s = s:gsub("negative zero", "zero") s = s .. fraction_text if hyphenate then s = s:gsub("%s", "-") end if capitalize then s = s:gsub("^%l", string.upper) end return s end local function _numeral_to_english2(args) local num = tostring(args.num) num = num:gsub("^%s*(.-)%s*$", "%1") -- Trim whitespace num = num:gsub(",", "") -- Remove commas num = num:gsub("^<span[^<>]*></span>", "") -- Generated by Template:age if num ~= '' then -- a fraction may have an empty whole number if not num:find("^%-?%d*%.?%d*%-?[Ee]?[+%-]?%d*$") then -- Input not in a valid format, try to eval it as an expr to see -- if that produces a number (e.g. "3 + 5" will become "8"). local noerr, result = pcall(mw.ext.ParserFunctions.expr, num) if noerr then num = result end end end -- Call helper function passing args return _numeral_to_english( num, args['numerator'], args['denominator'], args['capitalize'], args['use_and'], args['hyphenate'], args['ordinal'], args['plural'], args['links'], args['negative_word'], args['round'], args['zero'], args['use_one'] ) or '' end local p = { -- Functions that can be called from another module roman_to_numeral = roman_to_numeral, spell_number = _numeral_to_english, spell_number2 = _numeral_to_english2, english_to_ordinal = english_to_ordinal, english_to_numeral = english_to_numeral, } function p._roman_to_numeral(frame) -- Callable via {{#invoke:ConvertNumeric|_roman_to_numeral|VI}} return roman_to_numeral(frame.args[1]) end function p._english_to_ordinal(frame) -- callable via {{#invoke:ConvertNumeric|_english_to_ordinal|First}} return english_to_ordinal(frame.args[1]) end function p._english_to_numeral(frame) -- callable via {{#invoke:ConvertNumeric|_english_to_numeral|One}} return english_to_numeral(frame.args[1]) end function p.numeral_to_english(frame) local args = frame.args -- Tail call to helper function passing args from frame return _numeral_to_english2{ ['num'] = args[1], ['numerator'] = args['numerator'], ['denominator'] = args['denominator'], ['capitalize'] = args['case'] == 'U' or args['case'] == 'u', ['use_and'] = args['sp'] ~= 'us', ['hyphenate'] = args['adj'] == 'on', ['ordinal'] = args['ord'] == 'on', ['plural'] = args['pl'] == 'on', ['links'] = args['lk'], ['negative_word'] = args['negative'], ['round'] = args['round'], ['zero'] = args['zero'], ['use_one'] = args['one'] == 'one' -- experiment: using '|one=one' makes fraction 2+1/2 give "two and one-half" instead of "two and a half" } end ---- recursive function for p.decToHex local function decToHexDigit(dec) local dig = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"} local div = math.floor(dec/16) local mod = dec-(16*div) if div >= 1 then return decToHexDigit(div)..dig[mod+1] else return dig[mod+1] end end -- I think this is supposed to be done with a tail call but first I want something that works at all ---- finds all the decimal numbers in the input text and hexes each of them function p.decToHex(frame) local args=frame.args local parent=frame.getParent(frame) local pargs={} if parent then pargs=parent.args end local text=args[1] or pargs[1] or "" local minlength=args.minlength or pargs.minlength or 1 minlength=tonumber(minlength) local prowl=mw.ustring.gmatch(text,"(.-)(%d+)") local output="" repeat local chaff,dec=prowl() if not(dec) then break end local hex=decToHexDigit(dec) while (mw.ustring.len(hex)<minlength) do hex="0"..hex end output=output..chaff..hex until false local chaff=mw.ustring.match(text,"(%D+)$") or "" return output..chaff end return p pnyw663d8z474xbg4qqu86tb8s9yiu2 Plantilla:Time ago 10 25985 116704 2025-07-05T15:28:40Z Aristorkle 14080 redirect 116704 wikitext text/x-wiki #REDIRECT [[Template:Tiempo pasao]] isx2qozw9nc00atei8riupx0jf13yjp Plantilla:Tiempo pasao 10 25986 116705 2025-07-05T15:29:19Z Aristorkle 14080 copied from enwiki 116705 wikitext text/x-wiki {{#invoke:Time ago|main}}<noinclude> {{documentation}} <!-- Categories go in the /doc subpage and interwikis go in Wikidata. --> </noinclude> mzprrwbd409g2cer41ys035v9oay1od Módulo:Date 828 25987 116707 2025-07-05T15:33:42Z Aristorkle 14080 copied from enwiki 116707 Scribunto text/plain -- 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 with date/time fields -- o = table of options for AM/PM or AD/BC or format, if any -- or return nothing if date is known to be invalid. -- Caller determines if the values in n are valid. -- A year must be positive ('1' to '9999'); use 'BC' for BC. -- In a y-m-d string, the year must be four digits to avoid ambiguity -- ('0001' to '9999'). The only way to enter year <= 0 is by specifying -- the date as three numeric parameters like ymd Date(-1, 1, 1). -- Dates of form d/m/y, m/d/y, y/m/d are rejected as potentially ambiguous. local date, options = {}, {} if text:sub(-1) == 'Z' then -- Extract date/time from a Wikidata timestamp. -- The year can be 1 to 16 digits but this module handles 1 to 4 digits only. -- Examples: '+2016-06-21T14:30:00Z', '-0000000180-00-00T00:00:00Z'. local sign, y, m, d, H, M, S = text:match('^([+%-])(%d+)%-(%d%d)%-(%d%d)T(%d%d):(%d%d):(%d%d)Z$') if sign then y = tonumber(y) if sign == '-' and y > 0 then y = -y end if y <= 0 then options.era = 'BCE' end date.year = y m = tonumber(m) d = tonumber(d) H = tonumber(H) M = tonumber(M) S = tonumber(S) if m == 0 then newdate.partial = true return date, options end date.month = m if d == 0 then newdate.partial = true return date, options end date.day = d if H > 0 or M > 0 or S > 0 then date.hour = H date.minute = M date.second = S end return date, options end return end local function extract_ymd(item) -- Called when no day or month has been set. local y, m, d = item:match('^(%d%d%d%d)%-(%w+)%-(%d%d?)$') if y then if date.year then return end if m:match('^%d%d?$') then m = tonumber(m) else m = month_number(m) end if m then date.year = tonumber(y) date.month = m date.day = tonumber(d) return true end end end local function extract_day_or_year(item) -- Called when a day would be valid, or -- when a year would be valid if no year has been set and partial is set. local number, suffix = item:match('^(%d%d?%d?%d?)(.*)$') if number then local n = tonumber(number) if #number <= 2 and n <= 31 then suffix = suffix:lower() if suffix == '' or suffix == 'st' or suffix == 'nd' or suffix == 'rd' or suffix == 'th' then date.day = n return true end elseif suffix == '' and newdate.partial and not date.year then date.year = n return true end end end local function extract_month(item) -- A month must be given as a name or abbreviation; a number could be ambiguous. local m = month_number(item) if m then date.month = m return true end end local function extract_time(item) local h, m, s = item:match('^(%d%d?):(%d%d)(:?%d*)$') if date.hour or not h then return end if s ~= '' then s = s:match('^:(%d%d)$') if not s then return end end date.hour = tonumber(h) date.minute = tonumber(m) date.second = tonumber(s) -- nil if empty string return true end local item_count = 0 local index_time local function set_ampm(item) local H = date.hour if H and not options.am and index_time + 1 == item_count then options.am = ampm_options[item] -- caller checked this is not nil if item:match('^[Aa]') then if not (1 <= H and H <= 12) then return end if H == 12 then date.hour = 0 end else if not (1 <= H and H <= 23) then return end if H <= 11 then date.hour = H + 12 end end return true end end for item in text:gsub(',', ' '):gsub('&nbsp;', ' '):gmatch('%S+') do item_count = item_count + 1 if era_text[item] then -- Era is accepted in peculiar places. if options.era then return end options.era = item elseif ampm_options[item] then if not set_ampm(item) then return end elseif item:find(':', 1, true) then if not extract_time(item) then return end index_time = item_count elseif date.day and date.month then if date.year then return -- should be nothing more so item is invalid end if not item:match('^(%d%d?%d?%d?)$') then return end date.year = tonumber(item) elseif date.day then if not extract_month(item) then return end elseif date.month then if not extract_day_or_year(item) then return end elseif extract_month(item) then options.format = 'mdy' elseif extract_ymd(item) then options.format = 'ymd' elseif extract_day_or_year(item) then if date.day then options.format = 'dmy' end else return end end if not date.year or date.year == 0 then return end local era = era_text[options.era] if era and era.isbc then date.year = 1 - date.year end return date, options end local function autofill(date1, date2) -- Fill any missing month or day in each date using the -- corresponding component from the other date, if present, -- or with 1 if both dates are missing the month or day. -- This gives a good result for calculating the difference -- between two partial dates when no range is wanted. -- Return filled date1, date2 (two full dates). local function filled(a, b) -- Return date a filled, if necessary, with month and/or day from date b. -- The filled day is truncated to fit the number of days in the month. local fillmonth, fillday if not a.month then fillmonth = b.month or 1 end if not a.day then fillday = b.day or 1 end if fillmonth or fillday then -- need to create a new date a = Date(a, { month = fillmonth, day = math.min(fillday or a.day, days_in_month(a.year, fillmonth or a.month, a.calendar)) }) end return a end return filled(date1, date2), filled(date2, date1) end local function date_add_sub(lhs, rhs, is_sub) -- Return a new date from calculating (lhs + rhs) or (lhs - rhs), -- or return nothing if invalid. -- The result is nil if the calculated date exceeds allowable limits. -- Caller ensures that lhs is a date; its properties are copied for the new date. if lhs.partial then -- Adding to a partial is not supported. -- Can subtract a date or partial from a partial, but this is not called for that. return end local function is_prefix(text, word, minlen) local n = #text return (minlen or 1) <= n and n <= #word and text == word:sub(1, n) end local function do_days(n) local forcetime, jd if floor(n) == n then jd = lhs.jd else forcetime = not lhs.hastime jd = lhs.jdz end jd = jd + (is_sub and -n or n) if forcetime then jd = tostring(jd) if not jd:find('.', 1, true) then jd = jd .. '.0' end end return Date(lhs, 'juliandate', jd) end if type(rhs) == 'number' then -- Add/subtract days, including fractional days. return do_days(rhs) end if type(rhs) == 'string' then -- rhs is a single component like '26m' or '26 months' (with optional sign). -- Fractions like '3.25d' are accepted for the units which are handled as days. local sign, numstr, id = rhs:match('^%s*([+-]?)([%d%.]+)%s*(%a+)$') if sign then if sign == '-' then is_sub = not (is_sub and true or false) end local y, m, days local num = tonumber(numstr) if not num then return end id = id:lower() if is_prefix(id, 'years') then y = num m = 0 elseif is_prefix(id, 'months') then y = floor(num / 12) m = num % 12 elseif is_prefix(id, 'weeks') then days = num * 7 elseif is_prefix(id, 'days') then days = num elseif is_prefix(id, 'hours') then days = num / 24 elseif is_prefix(id, 'minutes', 3) then days = num / (24 * 60) elseif is_prefix(id, 'seconds') then days = num / (24 * 3600) else return end if days then return do_days(days) end if numstr:find('.', 1, true) then return end if is_sub then y = -y m = -m end assert(-11 <= m and m <= 11) y = lhs.year + y m = lhs.month + m if m > 12 then y = y + 1 m = m - 12 elseif m < 1 then y = y - 1 m = m + 12 end local d = math.min(lhs.day, days_in_month(y, m, lhs.calendar)) return Date(lhs, y, m, d) end end if is_diff(rhs) then local days = rhs.age_days if (is_sub or false) ~= (rhs.isnegative or false) then days = -days end return lhs + days end end local full_date_only = { dayabbr = true, dayname = true, dow = true, dayofweek = true, dowiso = true, dayofweekiso = true, dayofyear = true, gsd = true, juliandate = true, jd = true, jdz = true, jdnoon = true, } -- Metatable for a date's calculated fields. local datemt = { __index = function (self, key) if rawget(self, 'partial') then if full_date_only[key] then return end if key == 'monthabbr' or key == 'monthdays' or key == 'monthname' then if not self.month then return end end end local value if key == 'dayabbr' then value = day_info[self.dow][1] elseif key == 'dayname' then value = day_info[self.dow][2] elseif key == 'dow' then value = (self.jdnoon + 1) % 7 -- day-of-week 0=Sun to 6=Sat elseif key == 'dayofweek' then value = self.dow elseif key == 'dowiso' then value = (self.jdnoon % 7) + 1 -- ISO day-of-week 1=Mon to 7=Sun elseif key == 'dayofweekiso' then value = self.dowiso elseif key == 'dayofyear' then local first = Date(self.year, 1, 1, self.calendar).jdnoon value = self.jdnoon - first + 1 -- day-of-year 1 to 366 elseif key == 'era' then -- Era text (never a negative sign) from year and options. value = get_era_for_year(self.options.era, self.year) elseif key == 'format' then value = self.options.format or 'dmy' elseif key == 'gsd' then -- GSD = 1 from 00:00:00 to 23:59:59 on 1 January 1 AD Gregorian calendar, -- which is from jd 1721425.5 to 1721426.49999. value = floor(self.jd - 1721424.5) elseif key == 'juliandate' or key == 'jd' or key == 'jdz' then local jd, jdz = julian_date(self) rawset(self, 'juliandate', jd) rawset(self, 'jd', jd) rawset(self, 'jdz', jdz) return key == 'jdz' and jdz or jd elseif key == 'jdnoon' then -- Julian date at noon (an integer) on the calendar day when jd occurs. value = floor(self.jd + 0.5) elseif key == 'isleapyear' then value = is_leap_year(self.year, self.calendar) elseif key == 'monthabbr' then value = month_info[self.month][1] elseif key == 'monthdays' then value = days_in_month(self.year, self.month, self.calendar) elseif key == 'monthname' then value = month_info[self.month][2] end if value ~= nil then rawset(self, key, value) return value end end, } -- Date operators. local function mt_date_add(lhs, rhs) if not is_date(lhs) then lhs, rhs = rhs, lhs -- put date on left (it must be a date for this to have been called) end return date_add_sub(lhs, rhs) end local function mt_date_sub(lhs, rhs) if is_date(lhs) then if is_date(rhs) then return DateDiff(lhs, rhs) end return date_add_sub(lhs, rhs, true) end end local function mt_date_concat(lhs, rhs) return tostring(lhs) .. tostring(rhs) end local function mt_date_tostring(self) return self:text() end local function mt_date_eq(lhs, rhs) -- Return true if dates identify same date/time where, for example, -- Date(-4712, 1, 1, 'Julian') == Date(-4713, 11, 24, 'Gregorian') is true. -- This is called only if lhs and rhs have the same type and the same metamethod. if lhs.partial or rhs.partial then -- One date is partial; the other is a partial or a full date. -- The months may both be nil, but must be the same. return lhs.year == rhs.year and lhs.month == rhs.month and lhs.calendar == rhs.calendar end return lhs.jdz == rhs.jdz end local function mt_date_lt(lhs, rhs) -- Return true if lhs < rhs, for example, -- Date('1 Jan 2016') < Date('06:00 1 Jan 2016') is true. -- This is called only if lhs and rhs have the same type and the same metamethod. if lhs.partial or rhs.partial then -- One date is partial; the other is a partial or a full date. if lhs.calendar ~= rhs.calendar then return lhs.calendar == 'Julian' end if lhs.partial then lhs = lhs.partial.first end if rhs.partial then rhs = rhs.partial.first end end return lhs.jdz < rhs.jdz end --[[ Examples of syntax to construct a date: Date(y, m, d, 'julian') default calendar is 'gregorian' Date(y, m, d, H, M, S, 'julian') Date('juliandate', jd, 'julian') if jd contains "." text output includes H:M:S Date('currentdate') Date('currentdatetime') Date('1 April 1995', 'julian') parse date from text Date('1 April 1995 AD', 'julian') using an era sets a flag to do the same for output Date('04:30:59 1 April 1995', 'julian') Date(date) copy of an existing date Date(date, t) same, updated with y,m,d,H,M,S fields from table t Date(t) date with y,m,d,H,M,S fields from table t ]] function Date(...) -- for forward declaration above -- Return a table holding a date assuming a uniform calendar always applies -- (proleptic Gregorian calendar or proleptic Julian calendar), or -- return nothing if date is invalid. -- A partial date has a valid year, however its month may be nil, and -- its day and time fields are nil. -- Field partial is set to false (if a full date) or a table (if a partial date). local calendars = { julian = 'Julian', gregorian = 'Gregorian' } local newdate = { _id = uniq, calendar = 'Gregorian', -- default is Gregorian calendar hastime = false, -- true if input sets a time hour = 0, -- always set hour/minute/second so don't have to handle nil minute = 0, second = 0, options = {}, list = _date_list, subtract = function (self, rhs, options) return DateDiff(self, rhs, options) end, text = _date_text, } local argtype, datetext, is_copy, jd_number, tnums local numindex = 0 local numfields = { 'year', 'month', 'day', 'hour', 'minute', 'second' } local numbers = {} for _, v in ipairs({...}) do v = strip_to_nil(v) local vlower = type(v) == 'string' and v:lower() or nil if v == nil then -- Ignore empty arguments after stripping so modules can directly pass template parameters. elseif calendars[vlower] then newdate.calendar = calendars[vlower] elseif vlower == 'partial' then newdate.partial = true elseif vlower == 'fix' then newdate.want_fix = true elseif is_date(v) then -- Copy existing date (items can be overridden by other arguments). if is_copy or tnums then return end is_copy = true newdate.calendar = v.calendar newdate.partial = v.partial newdate.hastime = v.hastime newdate.options = v.options newdate.year = v.year newdate.month = v.month newdate.day = v.day newdate.hour = v.hour newdate.minute = v.minute newdate.second = v.second elseif type(v) == 'table' then if tnums then return end tnums = {} local tfields = { year=1, month=1, day=1, hour=2, minute=2, second=2 } for tk, tv in pairs(v) do if tfields[tk] then tnums[tk] = tonumber(tv) end if tfields[tk] == 2 then newdate.hastime = true end end else local num = tonumber(v) if not num and argtype == 'setdate' and numindex == 1 then num = month_number(v) end if num then if not argtype then argtype = 'setdate' end if argtype == 'setdate' and numindex < 6 then numindex = numindex + 1 numbers[numfields[numindex]] = num elseif argtype == 'juliandate' and not jd_number then jd_number = num if type(v) == 'string' then if v:find('.', 1, true) then newdate.hastime = true end elseif num ~= floor(num) then -- The given value was a number. The time will be used -- if the fractional part is nonzero. newdate.hastime = true end else return end elseif argtype then return elseif type(v) == 'string' then if v == 'currentdate' or v == 'currentdatetime' or v == 'juliandate' then argtype = v else argtype = 'datetext' datetext = v end else return end end end if argtype == 'datetext' then if tnums or not set_date_from_numbers(newdate, extract_date(newdate, datetext)) then return end elseif argtype == 'juliandate' then newdate.partial = nil newdate.jd = jd_number if not set_date_from_jd(newdate) then return end elseif argtype == 'currentdate' or argtype == 'currentdatetime' then newdate.partial = nil newdate.year = current.year newdate.month = current.month newdate.day = current.day if argtype == 'currentdatetime' then newdate.hour = current.hour newdate.minute = current.minute newdate.second = current.second newdate.hastime = true end newdate.calendar = 'Gregorian' -- ignore any given calendar name elseif argtype == 'setdate' then if tnums or not set_date_from_numbers(newdate, numbers) then return end elseif not (is_copy or tnums) then return end if tnums then newdate.jd = nil -- force recalculation in case jd was set before changes from tnums if not set_date_from_numbers(newdate, tnums) then return end end if newdate.partial then local year = newdate.year local month = newdate.month local first = Date(year, month or 1, 1, newdate.calendar) month = month or 12 local last = Date(year, month, days_in_month(year, month), newdate.calendar) newdate.partial = { first = first, last = last } else newdate.partial = false -- avoid index lookup end setmetatable(newdate, datemt) local readonly = {} local mt = { __index = newdate, __newindex = function(t, k, v) error('date.' .. tostring(k) .. ' is read-only', 2) end, __add = mt_date_add, __sub = mt_date_sub, __concat = mt_date_concat, __tostring = mt_date_tostring, __eq = mt_date_eq, __lt = mt_date_lt, } return setmetatable(readonly, mt) end local function _diff_age(diff, code, options) -- Return a tuple of integer values from diff as specified by code, except that -- each integer may be a list of two integers for a diff with a partial date, or -- return nil if the code is not supported. -- If want round, the least significant unit is rounded to nearest whole unit. -- For a duration, an extra day is added. local wantround, wantduration, wantrange if type(options) == 'table' then wantround = options.round wantduration = options.duration wantrange = options.range else wantround = options end if not is_diff(diff) then local f = wantduration and 'duration' or 'age' error(f .. ': need a date difference (use "diff:' .. f .. '()" with a colon)', 2) end if diff.partial then -- Ignore wantround, wantduration. local function choose(v) if type(v) == 'table' then if not wantrange or v[1] == v[2] then -- Example: Date('partial', 2005) - Date('partial', 2001) gives -- diff.years = { 3, 4 } to show the range of possible results. -- If do not want a range, choose the second value as more expected. return v[2] end end return v end if code == 'ym' or code == 'ymd' then if not wantrange and diff.iszero then -- This avoids an unexpected result such as -- Date('partial', 2001) - Date('partial', 2001) -- giving diff = { years = 0, months = { 0, 11 } } -- which would be reported as 0 years and 11 months. return 0, 0 end return choose(diff.partial.years), choose(diff.partial.months) end if code == 'y' then return choose(diff.partial.years) end if code == 'm' or code == 'w' or code == 'd' then return choose({ diff.partial.mindiff:age(code), diff.partial.maxdiff:age(code) }) end return nil end local extra_days = wantduration and 1 or 0 if code == 'wd' or code == 'w' or code == 'd' then local offset = wantround and 0.5 or 0 local days = diff.age_days + extra_days if code == 'wd' or code == 'd' then days = floor(days + offset) if code == 'd' then return days end return floor(days/7), days % 7 end return floor(days/7 + offset) end local H, M, S = diff.hours, diff.minutes, diff.seconds if code == 'dh' or code == 'dhm' or code == 'dhms' or code == 'h' or code == 'hm' or code == 'hms' or code == 'M' or code == 's' then local days = floor(diff.age_days + extra_days) local inc_hour if wantround then if code == 'dh' or code == 'h' then if M >= 30 then inc_hour = true end elseif code == 'dhm' or code == 'hm' then if S >= 30 then M = M + 1 if M >= 60 then M = 0 inc_hour = true end end elseif code == 'M' then if S >= 30 then M = M + 1 end else -- Nothing needed because S is an integer. end if inc_hour then H = H + 1 if H >= 24 then H = 0 days = days + 1 end end end if code == 'dh' or code == 'dhm' or code == 'dhms' then if code == 'dh' then return days, H elseif code == 'dhm' then return days, H, M else return days, H, M, S end end local hours = days * 24 + H if code == 'h' then return hours elseif code == 'hm' then return hours, M elseif code == 'M' or code == 's' then M = hours * 60 + M if code == 'M' then return M end return M * 60 + S end return hours, M, S end if wantround then local inc_hour if code == 'ymdh' or code == 'ymwdh' then if M >= 30 then inc_hour = true end elseif code == 'ymdhm' or code == 'ymwdhm' then if S >= 30 then M = M + 1 if M >= 60 then M = 0 inc_hour = true end end elseif code == 'ymd' or code == 'ymwd' or code == 'yd' or code == 'md' then if H >= 12 then extra_days = extra_days + 1 end end if inc_hour then H = H + 1 if H >= 24 then H = 0 extra_days = extra_days + 1 end end end local y, m, d = diff.years, diff.months, diff.days if extra_days > 0 then d = d + extra_days if d > 28 or code == 'yd' then -- Recalculate in case have passed a month. diff = diff.date1 + extra_days - diff.date2 y, m, d = diff.years, diff.months, diff.days end end if code == 'ymd' then return y, m, d elseif code == 'yd' then if y > 0 then -- It is known that diff.date1 > diff.date2. diff = diff.date1 - (diff.date2 + (y .. 'y')) end return y, floor(diff.age_days) elseif code == 'md' then return y * 12 + m, d elseif code == 'ym' or code == 'm' then if wantround then if d >= 16 then m = m + 1 if m >= 12 then m = 0 y = y + 1 end end end if code == 'ym' then return y, m end return y * 12 + m elseif code == 'ymw' then local weeks = floor(d/7) if wantround then local days = d % 7 if days > 3 or (days == 3 and H >= 12) then weeks = weeks + 1 end end return y, m, weeks elseif code == 'ymwd' then return y, m, floor(d/7), d % 7 elseif code == 'ymdh' then return y, m, d, H elseif code == 'ymwdh' then return y, m, floor(d/7), d % 7, H elseif code == 'ymdhm' then return y, m, d, H, M elseif code == 'ymwdhm' then return y, m, floor(d/7), d % 7, H, M end if code == 'y' then if wantround and m >= 6 then y = y + 1 end return y end return nil end local function _diff_duration(diff, code, options) if type(options) ~= 'table' then options = { round = options } end options.duration = true return _diff_age(diff, code, options) end -- Metatable for some operations on date differences. diffmt = { -- for forward declaration above __concat = function (lhs, rhs) return tostring(lhs) .. tostring(rhs) end, __tostring = function (self) return tostring(self.age_days) end, __index = function (self, key) local value if key == 'age_days' then if rawget(self, 'partial') then local function jdz(date) return (date.partial and date.partial.first or date).jdz end value = jdz(self.date1) - jdz(self.date2) else value = self.date1.jdz - self.date2.jdz end end if value ~= nil then rawset(self, key, value) return value end end, } function DateDiff(date1, date2, options) -- for forward declaration above -- Return a table with the difference between two dates (date1 - date2). -- The difference is negative if date1 is older than date2. -- Return nothing if invalid. -- If d = date1 - date2 then -- date1 = date2 + d -- If date1 >= date2 and the dates have no H:M:S time specified then -- date1 = date2 + (d.years..'y') + (d.months..'m') + d.days -- where the larger time units are added first. -- The result of Date(2015,1,x) + '1m' is Date(2015,2,28) for -- x = 28, 29, 30, 31. That means, for example, -- d = Date(2015,3,3) - Date(2015,1,31) -- gives d.years, d.months, d.days = 0, 1, 3 (excluding date1). if not (is_date(date1) and is_date(date2) and date1.calendar == date2.calendar) then return end local wantfill if type(options) == 'table' then wantfill = options.fill end local isnegative = false local iszero = false if date1 < date2 then isnegative = true date1, date2 = date2, date1 elseif date1 == date2 then iszero = true end -- It is known that date1 >= date2 (period is from date2 to date1). if date1.partial or date2.partial then -- Two partial dates might have timelines: ---------------------A=================B--- date1 is from A to B inclusive --------C=======D-------------------------- date2 is from C to D inclusive -- date1 > date2 iff A > C (date1.partial.first > date2.partial.first) -- The periods can overlap ('April 2001' - '2001'): -------------A===B------------------------- A=2001-04-01 B=2001-04-30 --------C=====================D------------ C=2001-01-01 D=2001-12-31 if wantfill then date1, date2 = autofill(date1, date2) else local function zdiff(date1, date2) local diff = date1 - date2 if diff.isnegative then return date1 - date1 -- a valid diff in case we call its methods end return diff end local function getdate(date, which) return date.partial and date.partial[which] or date end local maxdiff = zdiff(getdate(date1, 'last'), getdate(date2, 'first')) local mindiff = zdiff(getdate(date1, 'first'), getdate(date2, 'last')) local years, months if maxdiff.years == mindiff.years then years = maxdiff.years if maxdiff.months == mindiff.months then months = maxdiff.months else months = { mindiff.months, maxdiff.months } end else years = { mindiff.years, maxdiff.years } end return setmetatable({ date1 = date1, date2 = date2, partial = { years = years, months = months, maxdiff = maxdiff, mindiff = mindiff, }, isnegative = isnegative, iszero = iszero, age = _diff_age, duration = _diff_duration, }, diffmt) end end local y1, m1 = date1.year, date1.month local y2, m2 = date2.year, date2.month local years = y1 - y2 local months = m1 - m2 local d1 = date1.day + hms(date1) local d2 = date2.day + hms(date2) local days, time if d1 >= d2 then days = d1 - d2 else months = months - 1 -- Get days in previous month (before the "to" date) given December has 31 days. local dpm = m1 > 1 and days_in_month(y1, m1 - 1, date1.calendar) or 31 if d2 >= dpm then days = d1 - hms(date2) else days = dpm - d2 + d1 end end if months < 0 then years = years - 1 months = months + 12 end days, time = math.modf(days) local H, M, S = h_m_s(time) return setmetatable({ date1 = date1, date2 = date2, partial = false, -- avoid index lookup years = years, months = months, days = days, hours = H, minutes = M, seconds = S, isnegative = isnegative, iszero = iszero, age = _diff_age, duration = _diff_duration, }, diffmt) end return { _current = current, _Date = Date, _days_in_month = days_in_month, } 8htfjg7cmqlbgysia559pe52c5tetp5 Plantilla:Years or months ago 10 25988 116708 2025-07-05T15:36:11Z Aristorkle 14080 redirect 116708 wikitext text/x-wiki #REDIRECT [[Template:Años_o_meses_pasao]] gubm42s4ckoc0guaoyc952gs12qssu5 Plantilla:Años o meses pasao 10 25989 116709 2025-07-05T15:39:42Z Aristorkle 14080 copied from enwiki 116709 wikitext text/x-wiki <includeonly>{{#ifexpr:{{#if:{{{2|}}}|1|0}}=0 or abs( ({{{4|{{CURRENTMONTH}}}}}+{{{3|{{CURRENTYEAR}}}}}*12) - ({{{2|{{CURRENTMONTH}}}}}+{{{1|{{CURRENTYEAR}}}}}*12)) >= 12 |<!-- in years -->{{#expr:floor(abs( ( ({{{4|{{CURRENTMONTH}}}}}+{{{3|{{CURRENTYEAR}}}}}*12) - ({{{2|{{CURRENTMONTH}}}}}+{{{1|{{CURRENTYEAR}}}}}*12) ) / 12 ))}}&nbsp;{{#ifexpr:({{{4|{{CURRENTMONTH}}}}}+{{{3|{{CURRENTYEAR}}}}}*12) - ({{{2|{{CURRENTMONTH}}}}}+{{{1|{{CURRENTYEAR}}}}}*12) < 0 |<!-- future -->{{#ifexpr:ceil( ( ({{{4|{{CURRENTMONTH}}}}}+{{{3|{{CURRENTYEAR}}}}}*12) - ({{{2|{{CURRENTMONTH}}}}}+{{{1|{{CURRENTYEAR}}}}}*12) ) / 12 ) = -1|year's|years'}} |<!-- past/current -->{{#ifexpr:floor( ( ({{{4|{{CURRENTMONTH}}}}}+{{{3|{{CURRENTYEAR}}}}}*12) - ({{{2|{{CURRENTMONTH}}}}}+{{{1|{{CURRENTYEAR}}}}}*12) ) / 12 ) = 1|year|years}} }} |<!-- in months -->{{#expr:abs( ({{{4|{{CURRENTMONTH}}}}}+{{{3|{{CURRENTYEAR}}}}}*12) - ({{{2|{{CURRENTMONTH}}}}}+{{{1|{{CURRENTYEAR}}}}}*12) )}}&nbsp;{{#ifexpr:({{{4|{{CURRENTMONTH}}}}}+{{{3|{{CURRENTYEAR}}}}}*12) - ({{{2|{{CURRENTMONTH}}}}}+{{{1|{{CURRENTYEAR}}}}}*12) < 0 |<!-- future -->{{#ifexpr: ({{{4|{{CURRENTMONTH}}}}}+{{{3|{{CURRENTYEAR}}}}}*12) - ({{{2|{{CURRENTMONTH}}}}}+{{{1|{{CURRENTYEAR}}}}}*12) = -1|month's|months'}} |<!-- past/current -->{{#ifexpr: ({{{4|{{CURRENTMONTH}}}}}+{{{3|{{CURRENTYEAR}}}}}*12) - ({{{2|{{CURRENTMONTH}}}}}+{{{1|{{CURRENTYEAR}}}}}*12) = 1|month|months}} }} }} {{#ifexpr:({{{4|{{CURRENTMONTH}}}}}+{{{3|{{CURRENTYEAR}}}}}*12) - ({{{2|{{CURRENTMONTH}}}}}+{{{1|{{CURRENTYEAR}}}}}*12) < 0|time|ago}}</includeonly><noinclude> {{Documentation}} </noinclude> 39r0h3lbb09shxuplb40kq4j43hfio8 Módulo:Time ago/doc 828 25990 116711 2025-07-05T16:05:16Z Aristorkle 14080 Página creada con «{{module rating|protected}} The module “{{BASEPAGENAME}}” implements {{tl|Time ago}}. See the template's page for documentation. Test cases can be found at [[Template:Time ago/testcases]].» 116711 wikitext text/x-wiki {{module rating|protected}} The module “{{BASEPAGENAME}}” implements {{tl|Time ago}}. See the template's page for documentation. Test cases can be found at [[Template:Time ago/testcases]]. c7vhkndre7k7t8180j6pxz0znqxj14t Plantilla:Tiempo pasao/doc 10 25991 116712 2025-07-05T16:06:02Z Aristorkle 14080 copied from enwiki 116712 wikitext text/x-wiki {{Documentation subpage}} {{lua|Module:Time ago}} <!-- Categories go at the bottom of this page and interwikis go in Wikidata. --> The '''Time ago''' template calculates the amount of time which has passed since a provided timestamp. The result is a string similar to one of the examples below. This template ''should not'' be used with "subst" unless you don't want the stamp to change as the user refreshes the page. Note that due to Wikipedia's caching mechanisms, you may need to [[WP:PURGE|purge]] a page using this template to update the dynamic value. See the section [[#Purge|Purge]] below. The result is rounded down. "Month" is defined as 31 days. == Usage == * <code><nowiki>{{</nowiki>'''Time ago'''|''timestamp''<nowiki>}}</nowiki></code> The timestamp can be almost any solid, readable format but to avoid ambiguity mistakes, one of the styles below is preferred. * <code>magnitude</code> parameter can be set to explicitly use certain unit. Allowed values are: <code>seconds</code>, <code>minutes</code>, <code>hours</code>, <code>days</code>, <code>weeks</code>, <code>months</code> and <code>years</code>. * <code>min_magnitude</code> parameter can be set to use the specified unit or bigger units. Allowed values are: <code>seconds</code>, <code>minutes</code>, <code>hours</code>, <code>days</code>, <code>months</code> and <code>years</code>. * <code>ago</code> parameter can be set to override the default usage of the text "<code>ago</code>". If the parameter is blank but not missing (i.e. <code><nowiki>{{time ago|2008|ago=}}</nowiki></code>), then the text "ago" is suppressed altogether. For future dates, setting "ago" as blank but not missing will suppress the text "time" (i.e. "2 years" instead of "2 years' time"). === Spelling out numbers === Numbers from 1 to 100 can be spelled out in their equivalent English word by using the <code>spellout</code> parameter. If <code>spellout</code> is set to "yes", "y", "true" or "1", all numbers from 1 to 100 will be spelled out. If <code>spellout</code> is set to "auto", only numbers from 1 to 9 will be spelled out, as per the recommendations at [[MOS:NUMERAL]]. It is also possible to set a custom maximum value for spelling out by using the <code>spelloutmax</code> parameter. For example, setting {{para|spellout|yes}} and {{para|spelloutmax|24}} will result in all numbers less than or equal to 24 being spelled out, and all numbers greater than 24 appearing as numerals. === Numeric output === Add {{para|numeric|y}} to print the number only (no text). === Purge link === Add the parameter {{para|purge|yes}} to add a [[WP:PURGE|purge]] link. == Examples == * {{tlc|Time ago| -83 minutes}} → '''{{Time ago|-83 minutes}}''' * {{tlc|Time ago| -334 minutes}} → '''{{Time ago|-334 minutes}}''' * {{tlc|Time ago| +334 minutes}} → '''{{Time ago|+334 minutes}}''' * {{tlc|Time ago| -334 minutes|3=ago=}} → '''{{Time ago|-334 minutes|ago=}}''' * {{tlc|Time ago|1901}} → '''{{Time ago|1901}}''' * {{tlc|Time ago|<nowiki>{{REVISIONTIMESTAMP}}</nowiki>}} → '''{{Time ago|{{REVISIONTIMESTAMP}}}}''' * {{tlc|Time ago| Jan 21, 2001 3:45 PM}} → '''{{Time ago|Jan 21 2001 3:45 PM}}''' * ''Wrong:'' {{tlc|Time ago| 3:45 pm, 21 Jan 2001}} → '''{{Time ago|3:45 pm, 21 Jan 2001}}''' * {{tlc|Time ago|20010121154500}} → '''{{Time ago|20010121154500}}''' * {{tlc|Time ago| Nov 6 2008}} → '''{{Time ago|Nov 6 2008}}''' * {{tlc|Time ago| Nov 6 2008|3=magnitude=weeks}} → '''{{Time ago| Nov 6 2008|magnitude=weeks}}''' * {{tlc|Time ago| Nov 6 2008|3=min_magnitude=days}} → '''{{Time ago|Nov 6 2008|min_magnitude=days}}''' * {{tlc|Time ago| Nov 6 2008|3=min_magnitude=years}} → '''{{Time ago|Nov 6 2008|min_magnitude=years}}''' * {{tlc|Time ago| Nov 6 2008|3=ago=in the past}} → '''{{Time ago|Nov 6 2008|ago=in the past}}''' * {{tlc|Time ago| Nov 6 2008|3=purge=yes}} → '''{{Time ago|Nov 6 2008|purge=yes}}''' * {{tlc|Time ago| 2008-11-06}} → '''{{Time ago|2008-11-06}}''' * <code><nowiki>{{Time ago| June 1, 2009|spellout=yes}}</nowiki></code> &rarr; '''{{time ago|June 1, 2009|spellout=yes}}''' * <code><nowiki>{{Time ago| June 1, 1999|spellout=yes}}</nowiki></code> &rarr; '''{{time ago|June 1, 1999|spellout=yes}}''' * <code><nowiki>{{Time ago| June 1, 2009|spellout=auto}}</nowiki></code> &rarr; '''{{time ago|June 1, 2009|spellout=auto}}''' * <code><nowiki>{{Time ago| June 1, 1999|spellout=auto}}</nowiki></code> &rarr; '''{{time ago|June 1, 1999|spellout=auto}}''' * <code><nowiki>{{Time ago| June 1, 1989|spellout=yes|spelloutmax=15}}</nowiki></code> &rarr; '''{{time ago|June 1, 1989|spellout=yes|spelloutmax=15}}''' * <code><nowiki>{{Time ago| June 1, 1989|spellout=yes|spelloutmax=25}}</nowiki></code> &rarr; '''{{time ago|June 1, 1989|spellout=yes|spelloutmax=25}}''' * {{tlc|Time ago|195909}} → '''{{Time ago|195909}}''' * ''Wrong:'' {{tlc|Time ago|196009}} → '''{{Time ago|196009}}''' == TemplateData == {{TemplateDataHeader}} <templatedata> { "description": "This template calculates the amount of time which has passed since a provided timestamp.", "params": { "1": { "label": "Timestamp", "description": "Base timestamp for calculation of passed time. Example format: Nov 6 2008, see template documentation for other supported formats.", "type": "string", "required": true }, "magnitude": { "label": "magnitude", "description": "Explicitly sets a specific unit to display return value. Allowed values are: seconds, minutes, hours, days, weeks, months and years.", "type": "string", "required": false }, "min_magnitude": { "label": "min_magnitude", "description": "Sets a minimum unit to display return value. Allowed values are: seconds, minutes, hours, days, months and years.", "type": "string", "required": false }, "ago": { "label": "ago", "description": "Override the default usage of the text 'ago'. If it is blank but not missing then 'ago' will be removed completely; for future dates, this will remove the text 'time' as well.", "type": "string", "required": false }, "purge": { "label": "Purge link", "description": "Add the parameter purge=yes to add a WP:PURGE link.", "type": "string", "required": false }, "spellout": { "type": "string/line", "label": "Spell out numbers", "description": "If set to \"yes\", \"y\", \"true\" or \"1\", numbers from 1 to 100 are spelled out as English words. If set to \"auto\", numbers from 1 to 9 are spelled out." }, "spelloutmax": { "type": "number", "label": "Spell out max", "description": "The maximum number to be spelled out as an English word." } } } </templatedata> == See also == * {{tl|Last edited by}} * {{tl|Years or months ago}} * {{tl|Age}} * {{tl|Start date and age}} * {{tl|Birth date and age}} <includeonly>{{Sandbox other|| <!-- Categories go here and interwikis go in Wikidata --> [[Category:Mathematical time and date function templates]] [[Category:Date-computing templates based on current time]] }}</includeonly> ctp5lpfft8pui0y2h822zfgmartxrnv Módulo:Date/doc 828 25992 116716 2025-07-05T16:42:03Z Aristorkle 14080 copied from enwiki 116716 wikitext text/x-wiki This module provides date functions for use by other modules. Dates in the [[Gregorian calendar]] and the [[Julian calendar]] are supported, from 9999 BCE to 9999 CE. The calendars are proleptic—they are assumed to apply at all times with no irregularities. A date, with an optional time, can be specified in a variety of formats, and can be converted for display using a variety of formats, for example, 1 April 2016 or April 1, 2016. The properties of a date include its [[Julian day|Julian date]] and its [[Gregorian date|Gregorian]] serial date, as well as the day-of-week and day-of-year. Dates can be compared (for example, <code>date1 <= date2</code>), and can be used with add or subtract (for example, <code>date + '3 months'</code>). The difference between two dates can be determined with <code>date1 - date2</code>. These operations work with both Gregorian and Julian calendar dates, but <code>date1 - date2</code> is nil if the two dates use different calendars. The module provides the following items. {| class="wikitable" ! Export !! Description |- | <code>_current</code> || Table with the current year, month, day, hour, minute, second. |- | <code>_Date</code> || Function that returns a table for a specified date. |- | <code>_days_in_month</code> || Function that returns the number of days in a month. |} The following has examples of using the module: *[[Module:Date/example]] • Demonstration showing how Module:Date may be used. *[[Module talk:Date/example]] • Output from the demonstration. == Formatted output == A date can be formatted as text. <syntaxhighlight lang="lua"> local Date = require('Module:Date')._Date local text = Date(2016, 7, 1):text() -- result is '1 July 2016' local text = Date(2016, 7, 1):text('%-d %B') -- result is '1 July' local text = Date('1 July 2016'):text('mdy') -- result is 'July 1, 2016' </syntaxhighlight> The following simplified formatting codes are available. {| class="wikitable" ! Code !! Result |- | hm || hour:minute, with "am" or "pm" or variant, if specified (14:30 or 2:30&nbsp;pm or variant) |- | hms || hour:minute:second (14:30:45) |- | ymd || year-month-day (2016-07-01) |- | mdy || month day, year (July 1, 2016) |- | dmy || day month year (1 July 2016) |} The following formatting codes (similar to [[strftime]]) are available. {| class="wikitable" ! Code !! Result |- | %a || Day abbreviation: Mon, Tue, ... |- | %A || Day name: Monday, Tuesday, ... |- | %u || Day of week: 1 to 7 (Monday to Sunday) |- | %w || Day of week: 0 to 6 (Sunday to Saturday) |- | %d || Day of month zero-padded: 01 to 31 |- | %b || Month abbreviation: Jan to Dec |- | %B || Month name: January to December |- | %m || Month zero-padded: 01 to 12 |- | %Y || Year zero-padded: 0012, 0120, 1200 |- | %H || Hour 24-hour clock zero-padded: 00 to 23 |- | %I || Hour 12-hour clock zero-padded: 01 to 12 |- | %p || AM or PM or as in options |- | %M || Minute zero-padded: 00 to 59 |- | %S || Second zero-padded: 00 to 59 |- | %j || Day of year zero-padded: 001 to 366 |- | %-d || Day of month: 1 to 31 |- | %-m || Month: 1 to 12 |- | %-Y || Year: 12, 120, 1200 |- | %-H || Hour: 0 to 23 |- | %-M || Minute: 0 to 59 |- | %-S || Second: 0 to 59 |- | %-j || Day of year: 1 to 366 |- | %-I || Hour: 1 to 12 |- | %% || % |} In addition, <code>%{''property''}</code> (where <code>''property''</code> is any property of a date) can be used. For example, <code>Date('1 Feb 2015 14:30:45 A.D.')</code> has the following properties. {| class="wikitable" ! Code !! Result |- | %{calendar} || Gregorian |- | %{year} || 2015 |- | %{month} || 2 |- | %{day} || 1 |- | %{hour} || 14 |- | %{minute} || 30 |- | %{second} || 45 |- | %{dayabbr} || Sun |- | %{dayname} || Sunday |- | %{dayofweek} || 0 |- | %{dow} || 0 (same as dayofweek) |- | %{dayofweekiso} || 7 |- | %{dowiso} || 7 (same as dayofweekiso) |- | %{dayofyear} || 32 |- | %{era} || A.D. |- | %{gsd} || 735630 (numbers of days from 1 January 1 CE; the first is day 1) |- | %{juliandate} || 2457055.1046875 ([[Julian day]]) |- | %{jd} || 2457055.1046875 (same as juliandate) |- | %{isleapyear} || false |- | %{monthdays} || 28 |- | %{monthabbr} || Feb |- | %{monthname} || February |} Some shortcuts are available. Given <code>date = Date('1 Feb 2015 14:30')</code>, the following results would occur. {| class="wikitable" ! Code !! Description !! Example result !! Equivalent format |- | date:text('%c') || date and time || 2:30&nbsp;pm 1 February 2015 || %-I:%M %p %-d %B %-Y %{era} |- | date:text('%x') || date || 1 February 2015 || %-d %B %-Y %{era} |- | date:text('%X') || time || 2:30&nbsp;pm || %-I:%M %p |} == Julian date == The following has an example of converting a [[Julian day|Julian date]] to a date, then obtaining information about the date. <syntaxhighlight lang="lua"> -- Code -- Result Date = require('Module:Date')._Date date = Date('juliandate', 320) number = date.gsd -- -1721105 number = date.jd -- 320 text = date.dayname -- Saturday text = date:text() -- 9 October 4713&nbsp;BC text = date:text('%Y-%m-%d') -- 4713-10-09 text = date:text('%{era} %Y-%m-%d') -- BC 4713-10-09 text = date:text('%Y-%m-%d %{era}') -- 4713-10-09&nbsp;BC text = date:text('%Y-%m-%d %{era}', 'era=B.C.E.') -- 4713-10-09&nbsp;B.C.E. text = date:text('%Y-%m-%d', 'era=BCNEGATIVE') -- -4712-10-09 text = date:text('%Y-%m-%d', 'era=BCMINUS') -- −4712-10-09 (uses Unicode MINUS SIGN U+2212) text = Date('juliandate',320):text('%{gsd} %{jd}') -- -1721105 320 text = Date('Oct 9, 4713 B.C.E.'):text('%{gsd} %{jd}') -- -1721105 320 text = Date(-4712,10,9):text('%{gsd} %{jd}') -- -1721105 320 </syntaxhighlight> == Date differences == The difference between two dates can be determined with <code>date1 - date2</code>. The result is valid if both dates use the Gregorian calendar or if both dates use the Julian calendar, otherwise the result is nil. An age and duration can be calculated from a date difference. For example: <syntaxhighlight lang="lua"> -- Code -- Result Date = require('Module:Date')._Date date1 = Date('21 Mar 2015') date2 = Date('4 Dec 1999') diff = date1 - date2 d = diff.age_days -- 5586 y, m, d = diff.years, diff.months, diff.days -- 15, 3, 17 (15 years + 3 months + 17 days) y, m, d = diff:age('ymd') -- 15, 3, 17 y, m, w, d = diff:age('ymwd') -- 15, 3, 2, 3 (15 years + 3 months + 2 weeks + 3 days) y, m, w, d = diff:duration('ymwd') -- 15, 3, 2, 4 d = diff:duration('d') -- 5587 (a duration includes the final day) </syntaxhighlight> A date difference holds the original dates except they are swapped so <code>diff.date1 >= diff.date2</code> (<code>diff.date1</code> is the more recent date). This is shown in the following. <syntaxhighlight lang="lua"> date1 = Date('21 Mar 2015') date2 = Date('4 Dec 1999') diff = date1 - date2 neg = diff.isnegative -- false text = diff.date1:text() -- 21 March 2015 text = diff.date2:text() -- 4 December 1999 diff = date2 - date1 neg = diff.isnegative -- true (dates have been swapped) text = diff.date1:text() -- 21 March 2015 text = diff.date2:text() -- 4 December 1999 </syntaxhighlight> A date difference also holds a time difference: <syntaxhighlight lang="lua"> date1 = Date('8 Mar 2016 0:30:45') date2 = Date('19 Jan 2014 22:55') diff = date1 - date2 y, m, d = diff.years, diff.months, diff.days -- 2, 1, 17 H, M, S = diff.hours, diff.minutes, diff.seconds -- 1, 35, 45 </syntaxhighlight> A date difference can be added to a date, or subtracted from a date. <syntaxhighlight lang="lua"> date1 = Date('8 Mar 2016 0:30:45') date2 = Date('19 Jan 2014 22:55') diff = date1 - date2 date3 = date2 + diff date4 = date1 - diff text = date3:text('ymd hms') -- 2016-03-08 00:30:45 text = date4:text('ymd hms') -- 2014-01-19 22:55:00 equal = (date1 == date3) -- true equal = (date2 == date4) -- true </syntaxhighlight> The age and duration methods of a date difference accept a code that identifies the components that should be returned. An extra day is included for the duration method because it includes the final day. {| class="wikitable" ! Code !! Returned values |- | <code>'ymwd'</code> || years, months, weeks, days |- | <code>'ymd'</code> || years, months, days |- | <code>'ym'</code> || years, months |- | <code>'y'</code> || years |- | <code>'m'</code> || months |- | <code>'wd'</code> || weeks, days |- | <code>'w'</code> || weeks |- | <code>'d'</code> || days |} <includeonly>{{Sandbox other|| [[Category:Time, date and calendar modules]] }}</includeonly> <noinclude> [[Category:Module documentation pages]] </noinclude> j3wm30945m97lidq3q8omsjj2niw0uz Módulo:Age 828 25994 116719 2025-07-05T16:47:22Z Aristorkle 14080 copied from enwiki 116719 Scribunto text/plain -- 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-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', ['mt-warn-param1'] = 'Invalid parameter $1', ['mt-warn-param2'] = 'Parameter $1=$2 is invalid', ['txt-affirmative'] = { y = true, yes = true, Y = true, Yes = true, YES = true }, -- valid values for df + mf parameters ['txt-yes'] = { y = true, yes = true, on = true }, -- valid values for parameters introduced with this module ['txt-and'] = ' and ', ['txt-or'] = '&nbsp;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-warn-param1'] = true, ['mt-warn-param2'] = true, } -- yes[parameter] is true if parameter should be interpreted as "yes". -- Do not want to accept mixed upper/lowercase unless done by previously used templates. -- Need to accept "on" because "round=on" is wanted. local yes = mtext['txt-yes'] 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 local function getExports(frame) -- 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['txt-module-date'] .. sandbox) local 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 end local Collection -- a table to hold items Collection = { add = function (self, item) if item ~= nil then self.n = self.n + 1 self[self.n] = item end end, join = function (self, sep) return table.concat(self, sep) end, remove = function (self, pos) if self.n > 0 and (pos == nil or (0 < pos and pos <= self.n)) then self.n = self.n - 1 return table.remove(self, pos) end end, sort = function (self, comp) table.sort(self, comp) end, new = function () return setmetatable({n = 0}, Collection) end } Collection.__index = Collection local function stripToNil(text) -- If text is a string, return its trimmed content, or nil if empty. -- Otherwise return text (which may, for example, be nil). if type(text) == 'string' then text = text:match('(%S.-)%s*$') end return text end local function substituteParameters(text, ...) -- Return text after substituting any given parameters for $1, $2, etc. return mw.message.newRawMessage(text, ...):plain() end local function message(msg, ...) -- 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'], warning = mtext['txt-category'], } local a, b, k, category local text = substituteParameters(getText(msg), ...) if isWarning[msg] then a = '<sup>[<i>' b = '</i>]</sup>' k = 'warning' else a = '<strong class="error">' .. getText('txt-error') b = '</strong>' k = 'error' end if mw.title.getCurrentTitle():inNamespaces(0) then -- Category only in namespaces: 0=article. category = '[[' .. categories[k] .. ']]' end return a .. mw.text.nowiki(text) .. b .. (category or '') end local function dateFormat(args) -- Return -- nil, f if parameter is valid -- m, f otherwise -- where -- m = string for warning message with category -- f = string for wanted date format local problem local wanted = mtext['txt-format-default'] local other = wanted == 'df' and 'mf' or 'df' local parm = args[other] or '' if mtext['txt-affirmative'][parm] then wanted = other elseif parm ~= '' then problem = message('mt-warn-param2', other, parm) end return problem, wanted == 'df' and mtext['txt-dmy'] or mtext['txt-mdy'] end local function formatNumber(number) -- Return the given number formatted with commas as group separators, -- given that the number is an integer. local numstr = tostring(number) local length = #numstr local places = Collection.new() local pos = 0 repeat places:add(pos) pos = pos + 3 until pos >= length places:add(length) local groups = Collection.new() for i = places.n, 2, -1 do local p1 = length - places[i] + 1 local p2 = length - places[i - 1] groups:add(numstr:sub(p1, p2)) end return groups:join(',') end local function spellNumber(number, options, i) -- Return result of spelling number, or -- return number (as a string) if cannot spell it. -- i == 1 for the first number which can optionally start with an uppercase letter. number = tostring(number) return require(mtext['txt-module-convertnumeric']).spell_number( number, nil, -- fraction numerator nil, -- fraction denominator i == 1 and options.upper, -- true: 'One' instead of 'one' not options.us, -- true: use 'and' between tens/ones etc options.adj, -- true: hyphenated options.ordinal -- true: 'first' instead of 'one' ) or number end local function makeExtra(args, flagCurrent) -- Return extra text that will be inserted before the visible result -- but after any sort key. local extra = args.prefix or '' if mw.ustring.len(extra) > 1 then -- Parameter "~" gives "~3" whereas "over" gives "over 3". if extra:sub(-6, -1) ~= '&nbsp;' then extra = extra .. ' ' end end if flagCurrent then extra = '<span class="currentage"></span>' .. extra end return extra end local function makeSort(value, sortable) -- Return a sort key if requested. -- Assume value is a valid number which has not overflowed. if sortable == 'sortable_table' or sortable == 'sortable_on' or sortable == 'sortable_debug' then local sortKey if value == 0 then sortKey = '5000000000000000000' else local mag = math.floor(math.log10(math.abs(value)) + 1e-14) if value > 0 then sortKey = 7000 + mag else sortKey = 2999 - mag value = value + 10^(mag+1) end sortKey = string.format('%d', sortKey) .. string.format('%015.0f', math.floor(value * 10^(14-mag))) end local result if sortable == 'sortable_table' then result = 'data-sort-value="_SORTKEY_"|' elseif sortable == 'sortable_debug' then result = '<span data-sort-value="_SORTKEY_♠"><span style="border:1px solid">_SORTKEY_♠</span></span>' else result = '<span data-sort-value="_SORTKEY_♠"></span>' end return (result:gsub('_SORTKEY_', sortKey)) end end local translateParameters = { abbr = { off = 'abbr_off', on = 'abbr_on', }, disp = { age = 'disp_age', raw = 'disp_raw', }, format = { raw = 'format_raw', commas = 'format_commas', }, round = { on = 'on', yes = 'on', months = 'ym', weeks = 'ymw', days = 'ymd', hours = 'ymdh', }, sep = { comma = 'sep_comma', [','] = 'sep_comma', serialcomma = 'sep_serialcomma', space = 'sep_space', }, show = { hide = { id = 'hide' }, y = { 'y', id = 'y' }, ym = { 'y', 'm', id = 'ym' }, ymd = { 'y', 'm', 'd', id = 'ymd' }, ymw = { 'y', 'm', 'w', id = 'ymw' }, ymwd = { 'y', 'm', 'w', 'd', id = 'ymwd' }, yd = { 'y', 'd', id = 'yd', keepZero = true }, m = { 'm', id = 'm' }, md = { 'm', 'd', id = 'md' }, w = { 'w', id = 'w' }, wd = { 'w', 'd', id = 'wd' }, h = { 'H', id = 'h' }, 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' }, dhm = { 'd', 'H', 'M', id = 'dhm' }, dhms = { 'd', 'H', 'M', 'S', id = 'dhms' }, ymdh = { 'y', 'm', 'd', 'H', id = 'ymdh' }, ymdhm = { 'y', 'm', 'd', 'H', 'M', id = 'ymdhm' }, ymwdh = { 'y', 'm', 'w', 'd', 'H', id = 'ymwdh' }, ymwdhm = { 'y', 'm', 'w', 'd', 'H', 'M', id = 'ymwdhm' }, }, sortable = { off = false, on = 'sortable_on', table = 'sortable_table', debug = 'sortable_debug', }, } local spellOptions = { cardinal = {}, Cardinal = { upper = true }, cardinal_us = { us = true }, Cardinal_us = { us = true, upper = true }, ordinal = { ordinal = true }, Ordinal = { ordinal = true, upper = true }, ordinal_us = { ordinal = true, us = true }, Ordinal_us = { ordinal = true, us = true, upper = true }, } local function dateExtract(frame) -- Return part of a date after performing an optional operation. local Date = getExports(frame) local args = frame:getParent().args local parms = {} for i, v in ipairs(args) do parms[i] = v end if yes[args.fix] then table.insert(parms, 'fix') end if yes[args.partial] then table.insert(parms, 'partial') end local show = stripToNil(args.show) or 'dmy' local date = Date(unpack(parms)) if not date then if show == 'format' then return 'error' end return message('mt-need-valid-date') end local add = stripToNil(args.add) if add then for item in add:gmatch('%S+') do date = date + item if not date then return message('mt-cannot-add', item) end end end local sortKey, result local sortable = translateParameters.sortable[args.sortable] if sortable then local value = (date.partial and date.partial.first or date).jdz sortKey = makeSort(value, sortable) end if show ~= 'hide' then 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['txt-or'] end local function makeText(values, components, names, options, noUpper) -- Return wikitext representing an age or duration. local text = Collection.new() local count = #values local sep = names.sep or '' for i, v in ipairs(values) do -- v is a number (say 4 for 4 years), or a table ({4,5} for 4 or 5 years). local islist = type(v) == 'table' if (islist or v > 0) or (text.n == 0 and i == count) or (text.n > 0 and components.keepZero) then local fmt, vstr if options.spell then fmt = function(number) return spellNumber(number, options.spell, noUpper or i) end elseif i == 1 and options.format == 'format_commas' then -- Numbers after the first should be small and not need formatting. fmt = formatNumber else fmt = tostring end if islist then vstr = fmt(v[1]) .. rangeJoin(options.range) noUpper = true vstr = vstr .. fmt(v[2]) else vstr = fmt(v) end local name = names[components[i]] if name then if type(name) == 'table' then name = mw.getContentLanguage():plural(islist and v[2] or v, name) end text:add(vstr .. sep .. name) else text:add(vstr) end end end local first, last if options.join == 'sep_space' then first = ' ' last = ' ' elseif options.join == 'sep_comma' then first = ', ' last = ', ' 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 if i < text.n then text[i] = v .. (i + 1 < text.n and first or last) end end local sign = '' if options.isnegative then -- Do not display negative zero. if text.n > 1 or (text.n == 1 and text[1]:sub(1, 1) ~= '0' ) then if options.format == 'format_raw' then sign = '-' -- plain hyphen so result can be used in a calculation else sign = '−' -- Unicode U+2212 MINUS SIGN end end end return (options.sortKey or '') .. (options.extra or '') .. sign .. text:join() .. (options.suffix or '') end local function dateDifference(parms) -- Return a formatted date difference using the given parameters -- 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 = { 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 = { y = 'y', m = 'm', w = 'w', d = 'd', H = 'h', M = 'm', S = 's', }, abbr_infant = { -- for {{age for infant}} 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 = {}, } local diff = parms.diff -- must be a valid date difference local show = parms.show -- may be nil; default is set below local abbr = parms.abbr or 'abbr_off' local defaultJoin if abbr ~= 'abbr_off' then defaultJoin = 'sep_space' end if not show then show = 'ymd' if parms.disp == 'disp_age' then if diff.years < 3 then defaultJoin = 'sep_space' if diff.years >= 1 then show = 'ym' else show = 'md' end else show = 'y' end end end if type(show) ~= 'table' then show = translateParameters.show[show] end if parms.disp == 'disp_raw' then defaultJoin = 'sep_space' abbr = 'abbr_raw' elseif parms.wantSc then defaultJoin = 'sep_serialcomma' end local diffOptions = { round = parms.round, duration = parms.wantDuration, range = parms.range and true or nil, } local sortKey if parms.sortable then local value = diff.age_days + (parms.wantDuration and 1 or 0) -- days and fraction of a day if diff.isnegative then value = -value end sortKey = makeSort(value, parms.sortable) end local textOptions = { extra = parms.extra, format = parms.format, join = parms.sep or defaultJoin, isnegative = diff.isnegative, range = parms.range, sortKey = sortKey, spell = parms.spell, suffix = parms.suffix, -- not currently used } if show.id == 'hide' then return sortKey or '' end local values = { diff:age(show.id, diffOptions) } if values[1] then return makeText(values, show, names[abbr], textOptions) end if diff.partial then -- Handle a more complex range such as -- {{age_yd|20 Dec 2001|2003|range=yes}} → 1 year, 12 days or 2 years, 11 days local opt = { format = textOptions.format, join = textOptions.join, isnegative = textOptions.isnegative, spell = textOptions.spell, } return (textOptions.sortKey or '') .. makeText({ diff.partial.mindiff:age(show.id, diffOptions) }, show, names[abbr], opt) .. rangeJoin(textOptions.range) .. makeText({ diff.partial.maxdiff:age(show.id, diffOptions) }, show, names[abbr], opt, true) .. (textOptions.suffix or '') end return message('mt-bad-show', show.id) end local function getDates(frame, getopt) -- Parse template parameters and return one of: -- * date (a date table, if single) -- * date1, date2 (two date tables, if not single) -- * text (a string error message) -- A missing date is optionally replaced with the current date. -- If wantMixture is true, a missing date component is replaced -- from the current date, so can get a bizarre mixture of -- specified/current y/m/d as has been done by some "age" templates. -- Some results may be placed in table getopt. local Date, currentDate = getExports(frame) getopt = getopt or {} local function flagCurrent(text) -- This allows the calling template to detect if the current date has been used, -- that is, whether both dates have been entered in a template expecting two. -- For example, an infobox may want the age when an event occurred, not the current age. -- Don't bother detecting if wantMixture is used because not needed and it is a poor option. if not text then if getopt.noMissing then return nil -- this gives a nil date which gives an error end text = 'currentdate' if getopt.flag == 'usesCurrent' then getopt.usesCurrent = true end end return text end local args = frame:getParent().args local fields = {} local isNamed = args.year or args.year1 or args.year2 or args.month or args.month1 or args.month2 or args.day or args.day1 or args.day2 if isNamed then fields[1] = args.year1 or args.year fields[2] = args.month1 or args.month fields[3] = args.day1 or args.day fields[4] = args.year2 fields[5] = args.month2 fields[6] = args.day2 else for i = 1, 6 do fields[i] = args[i] end end local imax = 0 for i = 1, 6 do fields[i] = stripToNil(fields[i]) if fields[i] then imax = i 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 isZero(fields[i]) then fields[i] = nil getopt.partial = true end end end local fix = getopt.fix and 'fix' or '' local partialText = getopt.partial and 'partial' or '' local dates = {} if isNamed or imax >= 3 then local nrDates = getopt.single and 1 or 2 if getopt.wantMixture then -- Cannot be partial since empty fields are set from current. local components = { 'year', 'month', 'day' } for i = 1, nrDates * 3 do fields[i] = fields[i] or currentDate[components[i > 3 and i - 3 or i]] end for i = 1, nrDates do local index = i == 1 and 1 or 4 local y, m, d = 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 -- If partial dates are allowed, accept -- year only, or -- year and month only -- Do not accept year and day without a month because that makes no sense -- (and because, for example, Date('partial', 2001, nil, 12) sets day = nil, not 12). for i = 1, nrDates do local index = i == 1 and 1 or 4 local y, m, d = fields[index], fields[index+1], fields[index+2] if (getopt.partial and y and (m or not d)) or (y and m and d) then dates[i] = Date(fix, partialText, y, m, d) elseif not y and not m and not d then dates[i] = Date(flagCurrent()) end end end else getopt.textdates = true -- have parsed each date from a single text field dates[1] = Date(fix, partialText, flagCurrent(fields[1])) if not getopt.single then dates[2] = Date(fix, partialText, flagCurrent(fields[2])) end end if not dates[1] then return message(getopt.missing1 or 'mt-need-valid-ymd') end if getopt.single then return dates[1] end if not dates[2] then return message(getopt.missing2 or 'mt-need-valid-ymd2') end return dates[1], dates[2] end local function ageGeneric(frame) -- Return the result required by the specified template. -- Can use sortable=x where x = on/table/off/debug in any supported template. -- Some templates default to sortable=on but can be overridden. local name = frame.args.template if not name then return message('mt-template-x') end local args = frame:getParent().args local specs = { age_days = { -- {{age in days}} show = 'd', disp = 'disp_raw', }, age_days_nts = { -- {{age in days nts}} show = 'd', disp = 'disp_raw', format = 'format_commas', sortable = 'on', }, duration_days = { -- {{duration in days}} show = 'd', disp = 'disp_raw', duration = true, }, duration_days_nts = { -- {{duration in days nts}} show = 'd', disp = 'disp_raw', format = 'format_commas', sortable = 'on', duration = true, }, age_full_years = { -- {{age}} show = 'y', abbr = 'abbr_raw', flag = 'usesCurrent', omitZero = true, range = 'dash', }, age_full_years_nts = { -- {{age nts}} show = 'y', abbr = 'abbr_raw', format = 'format_commas', sortable = 'on', }, age_in_years = { -- {{age in years}} show = 'y', abbr = 'abbr_raw', negative = 'error', range = 'dash', }, age_in_years_nts = { -- {{age in years nts}} show = 'y', abbr = 'abbr_raw', negative = 'error', range = 'dash', format = 'format_commas', sortable = 'on', }, age_infant = { -- {{age for infant}} -- Do not set show because special processing is done later. abbr = yes[args.abbr] and 'abbr_infant' or 'abbr_off', disp = 'disp_age', sep = 'sep_space', sortable = 'on', }, age_m = { -- {{age in months}} show = 'm', disp = 'disp_raw', }, age_w = { -- {{age in weeks}} show = 'w', disp = 'disp_raw', }, age_wd = { -- {{age in weeks and days}} show = 'wd', }, age_yd = { -- {{age in years and days}} show = 'yd', format = 'format_commas', sep = args.sep ~= 'and' and 'sep_comma' or nil, }, age_yd_nts = { -- {{age in years and days nts}} show = 'yd', format = 'format_commas', sep = args.sep ~= 'and' and 'sep_comma' or nil, sortable = 'on', }, age_ym = { -- {{age in years and months}} show = 'ym', sep = 'sep_comma', }, age_ymd = { -- {{age in years, months and days}} show = 'ymd', range = true, }, age_ymwd = { -- {{age in years, months, weeks and days}} show = 'ymwd', wantMixture = true, }, } local spec = specs[name] if not spec then return message('mt-template-bad-name') end if name == 'age_days' then local su = stripToNil(args['show unit']) if su then if su == 'abbr' or su == 'full' then spec.disp = nil spec.abbr = su == 'abbr' and 'abbr_on' or nil end end end local partial, autofill local range = stripToNil(args.range) or spec.range if range then -- Suppose partial dates are used and age could be 11 or 12 years. -- "|range=" (empty value) has no effect (spec is used). -- "|range=yes" or spec.range == true sets range = true (gives "11 or 12") -- "|range=dash" or spec.range == 'dash' sets range = 'dash' (gives "11–12"). -- "|range=no" or spec.range == 'no' sets range = nil and fills each date in the diff (gives "12"). -- ("on" is equivalent to "yes", and "off" is equivalent to "no"). -- "|range=OTHER" sets range = nil and rejects partial dates. range = ({ dash = 'dash', off = 'no', no = 'no', [true] = true })[range] or yes[range] if range then partial = true -- accept partial dates with a possible age range for the result if range == 'no' then autofill = true -- missing month/day in first or second date are filled from other date or 1 range = nil end end end local getopt = { fix = yes[args.fix], flag = stripToNil(args.flag) or spec.flag, omitZero = spec.omitZero, partial = partial, wantMixture = spec.wantMixture, } local date1, date2 = getDates(frame, getopt) if type(date1) == 'string' then return date1 end local format = stripToNil(args.format) local spell = spellOptions[format] if format then format = 'format_' .. format elseif name == 'age_days' and getopt.textdates then format = 'format_commas' end local parms = { diff = date2:subtract(date1, { fill = autofill }), wantDuration = spec.duration or yes[args.duration], range = range, wantSc = yes[args.sc], show = args.show == 'hide' and 'hide' or spec.show, abbr = spec.abbr, disp = spec.disp, extra = makeExtra(args, getopt.usesCurrent and format ~= 'format_raw'), format = format or spec.format, round = yes[args.round], sep = spec.sep, sortable = translateParameters.sortable[args.sortable or spec.sortable], spell = spell, } if (spec.negative or frame.args.negative) == 'error' and parms.diff.isnegative then return message('mt-date-wrong-order') end return from_en(dateDifference(parms)) end local function isFake(args) -- Some templates have TemplateData with an auto value like "{{Birth date and age|YYYY|MM|DD}}". -- Return true if that appears to be the case so the caller can output nothing rather than an error. return args[1] == 'YYYY' end local function bda(frame) -- Implement [[Template:Birth date and age]]. local args = frame:getParent().args if isFake(args) then return '' end local options = { missing1 = 'mt-need-valid-bd', noMissing = true, single = true, } local date = getDates(frame, options) if type(date) == 'string' then return date -- error text end local Date = getExports(frame) local diff = Date('currentdate') - date if diff.isnegative or diff.years > 150 then return message('mt-invalid-bd-age') end local disp = mtext['txt-bda-disp'] local show = 'y' if diff.years < 2 then disp = 'disp_age' if diff.years == 0 and diff.months == 0 then show = 'd' else show = 'm' end end local problem, format = dateFormat(args) local result = substituteParameters( mtext['txt-bda'], date:text('%-Y-%m-%d'), from_en(date:text(format)), from_en(dateDifference({ diff = diff, show = show, abbr = 'abbr_off', disp = disp, sep = 'sep_space', })) ) .. (problem or '') local warnings = tonumber(frame.args.warnings) if warnings and warnings > 0 then local good = { df = true, mf = true, day = true, day1 = true, month = true, month1 = true, year = true, year1 = true, } local invalid local imax = options.textdates and 1 or 3 for k, _ in pairs(args) do if type(k) == 'number' then if k > imax then invalid = tostring(k) break end else if not good[k] then invalid = k break end end end if invalid then result = result .. message('mt-warn-param1', invalid) end end return result end local function dda(frame) -- Implement [[Template:Death date and age]]. local args = frame:getParent().args if isFake(args) then return '' end local options = { missing1 = 'mt-need-valid-dd', missing2 = 'mt-need-valid-bd2', noMissing = true, partial = true, } local date1, date2 = getDates(frame, options) if type(date1) == 'string' then return date1 end local diff = date1 - date2 if diff.isnegative then return message('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 if diff.partial then years = diff.partial.years years = type(years) == 'table' and years[2] or years else years = diff.years end if years > 150 then return message('mt-invalid-dates-age') end local fmt_date, fmt_ymd, problem if date1.day then -- y, m, d known problem, fmt_date = dateFormat(args) fmt_ymd = '%-Y-%m-%d' elseif date1.month then -- y, m known; d unknown fmt_date = '%B %-Y' fmt_ymd = '%-Y-%m-00' else -- y known; m, d unknown fmt_date = '%-Y' fmt_ymd = '%-Y-00-00' end local sortKey local sortable = translateParameters.sortable[args.sortable] if sortable then local value = (date1.partial and date1.partial.first or date1).jdz sortKey = makeSort(value, sortable) end local result = (sortKey or '') .. substituteParameters( mtext['txt-dda'], date1:text(fmt_ymd), from_en(date1:text(fmt_date)), from_en(dateDifference({ diff = diff, show = 'y', abbr = 'abbr_off', disp = mtext['txt-dda-disp'], range = 'dash', sep = 'sep_space', })) ) .. (problem or '') local warnings = tonumber(frame.args.warnings) if warnings and warnings > 0 then local good = { df = true, mf = true, } local invalid local imax = options.textdates and 2 or 6 for k, _ in pairs(args) do if type(k) == 'number' then if k > imax then invalid = tostring(k) break end else if not good[k] then invalid = k break end end end if invalid then result = result .. message('mt-warn-param1', invalid) end end return result end local function dateToGsd(frame) -- Implement [[Template:Gregorian serial date]]. -- Return Gregorian serial date of the given date, or the current date. -- The returned value is negative for dates before 1 January 1 AD -- despite the fact that GSD is not defined for such dates. local date = getDates(frame, { wantMixture=true, single=true }) if type(date) == 'string' then return date end return tostring(date.gsd) end local function jdToDate(frame) -- Return formatted date from a Julian date. -- The result includes a time if the input includes a fraction. -- The word 'Julian' is accepted for the Julian calendar. local Date = getExports(frame) local args = frame:getParent().args local date = Date('juliandate', args[1], args[2]) if date then return from_en(date:text()) end return message('mt-need-jdn') end local function dateToJd(frame) -- Return Julian date (a number) from a date which may include a time, -- or the current date ('currentdate') or current date and time ('currentdatetime'). -- The word 'Julian' is accepted for the Julian calendar. local Date = getExports(frame) local args = frame:getParent().args local date = Date(args[1], args[2], args[3], args[4], args[5], args[6], args[7]) if date then return tostring(date.jd) end return message('mt-need-valid-ymd-current') end local function timeInterval(frame) -- Implement [[Template:Time interval]]. -- There are two positional arguments: date1, date2. -- The default for each is the current date and time. -- Result is date2 - date1 formatted. local Date = getExports(frame) local args = frame:getParent().args local parms = { extra = makeExtra(args), wantDuration = yes[args.duration], range = yes[args.range] or (args.range == 'dash' and 'dash' or nil), wantSc = yes[args.sc], } local fix = yes[args.fix] and 'fix' or '' local date1 = Date(fix, 'partial', stripToNil(args[1]) or 'currentdatetime') if not date1 then return message('mt-invalid-start') end local date2 = Date(fix, 'partial', stripToNil(args[2]) or 'currentdatetime') if not date2 then return message('mt-invalid-end') end parms.diff = date2 - date1 for argname, translate in pairs(translateParameters) do local parm = stripToNil(args[argname]) if parm then parm = translate[parm] if parm == nil then -- test for nil because false is a valid setting return message('mt-bad-param2', argname, args[argname]) end parms[argname] = parm end end if parms.round then local round = parms.round local show = parms.show if round ~= 'on' then if show then if show.id ~= round then return message('mt-conflicting-show', args.show, args.round) end else parms.show = translateParameters.show[round] end end parms.round = true end return from_en(dateDifference(parms)) end local function templateGeneric(frame) local name = frame.args.template if not name then return message('mt-template-x') end return ageGeneric(frame:newChild{title = mw.title.new(name, 10), args = frame.args}) end return { age_generic = ageGeneric, -- can emulate several age templates birth_date_and_age = bda, -- Template:Birth_date_and_age death_date_and_age = dda, -- Template:Death_date_and_age gsd = dateToGsd, -- Template:Gregorian_serial_date extract = dateExtract, -- Template:Extract jd_to_date = jdToDate, -- Template:? JULIANDAY = dateToJd, -- Template:JULIANDAY time_interval = timeInterval, -- Template:Time_interval [''] = templateGeneric, -- same as age_generic, but can be invoked directly } qlkaap82oo8xun0m94f9ot3dz98pxmm