Mòdul:Date time
Aparença
La documentació d'ús d'aquest mòdul es pot crear a Mòdul:Date time/ús
--[[
Module:Date time – Mòdul de validació i format de dates.
Aquest mòdul proporciona funcions per validar i formatar dates a les plantilles.
Gestiona:
- Validació de components de data (any, mes, dia)
- Validació de components de temps (hora, minut, segon)
- Format i validació de la zona horària
- Generació de marcatge de microformat hCalendar adaptat
- Càlculs de "fa temps" (enllaçat amb Module:Time ago)
]]
require("strict")
local p = {}
---------------
-- Constants --
---------------
local HTML_SPACE = " "
local HTML_NBSP = " "
-- Constants de missatges d'error en català
local ERROR_MESSAGES = {
integers = "Tots els valors han de ser nombres enters",
has_leading_zeros = "Els valors no poden tenir zeros a l'esquerra innecessaris",
missing_year = "El valor de l'any és obligatori",
invalid_month = "El valor no és un mes vàlid",
missing_month = "El valor del mes és obligatori quan s'indica el dia",
invalid_day = "El valor no és un dia vàlid (El mes %d té %d dies)",
invalid_hour = "El valor no és una hora vàlida",
invalid_minute = "El valor no és un minut vàlid",
invalid_second = "El valor no és un segon vàlid",
timezone_incomplete_date = "No es pot establir una zona horària sense indicar el dia i l'hora",
invalid_timezone = "El valor no és una zona horària vàlida",
yes_value_parameter = '%s ha de ser "yes" o "y"',
duplicate_parameters = 'S\'han utilitzat paràmetres duplicats: %s i %s',
template = "Plantilla no compatible",
time_without_hour = "Els minuts i segons requereixen un valor d'hora"
}
-- Mapeig de classes de plantilla (adaptat per a microformats estàndard)
local TEMPLATE_CLASSES = {
["start date"] = "bday dtstart published updated itvstart",
["start date and age"] = "bday dtstart published updated",
["end date"] = "dtend itvend",
["end date and age"] = "dtend"
}
-- Plantilles que demanen el càlcul del temps passat
local TIME_AGO = {
["start date and age"] = true,
["end date and age"] = true
}
-- Noms dels mesos en català
local MONTHS = {
"gener", "febrer", "març", "abril", "maig", "juny",
"juliol", "agost", "setembre", "octubre", "novembre", "desembre"
}
-- Categoria d'error
local ERROR_CATEGORY = "[[Category:Pàgines amb errors en el mòdul de dates]]"
-- Espais de noms on s'aplica la categoria d'error
local CATEGORY_NAMESPACES = {
[0] = true, -- Article
[1] = true, -- Discussió d'article
[4] = true, -- Viquipèdia
[10] = true, -- Plantilla
[100] = true, -- Portal
[118] = true -- Esborrany
}
-- Memòria cau per a anys de traspàs per rendiment
local leap_year_cache = {}
-- Variables locals per a la gestió d'errors
local help_link
----------------------
-- Funcions Auxiliars --
----------------------
--- Afegeix zeros a l'esquerra per garantir un mínim de dos dígits.
local function pad_left_zeros(value)
if value == nil then
return nil
end
local str = tostring(value)
return string.rep("0", math.max(0, 2 - #str)) .. str
end
--- Reemplaça el menys d'Unicode pel guionet ASCII i viceversa.
local function replace_minus_character(value, to_unicode)
if not value then
return nil
end
if to_unicode then
return value:gsub("-", "−")
end
return value:gsub("−", "-")
end
--- Normalitza el format de la zona horària.
local function fix_timezone(timezone)
if not timezone then
return nil
end
timezone = replace_minus_character(timezone, false)
local sign, hour, minutes = timezone:match("^([+-])(%d+):(%d+)$")
if sign and hour and minutes then
hour = pad_left_zeros(hour)
return sign .. hour .. ":" .. minutes
end
return timezone
end
--- Comprova si una zona horària és vàlida (UTC-12:00 a UTC+14:00).
local function is_timezone_valid(timezone)
local valid_patterns = {
"^Z$",
"^[+]0[1-9]:[0-5][0-9]$",
"^[+-]0[1-9]:[0-5][0-9]$",
"^[+-]1[0-2]:[0-5][0-9]$",
"^[+]1[34]:[0-5][0-9]$",
"^[+-]0[1-9]$",
"^[+-]1[0-2]$",
"^[+]1[34]$",
"^[+]00:00$",
"^[+]00$"
}
if timezone == "-00" or timezone == "-00:00" then
return false
end
for _, pattern in ipairs(valid_patterns) do
if string.match(timezone, pattern) then
return true
end
end
return false
end
--- Comprova si un any és de traspàs.
local function is_leap_year(year)
if leap_year_cache[year] == nil then
leap_year_cache[year] = (year % 4 == 0 and year % 100 ~= 0) or (year % 400 == 0)
end
return leap_year_cache[year]
end
--- Retorna els dies que té un mes concret d'un any.
local function get_days_in_month(year, month)
local days_in_month = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
if month == 2 and is_leap_year(year) then
return 29
end
return days_in_month[month] or 0
end
--- Comprova si un valor conté zeros a l'esquerra no permesos.
local function has_leading_zeros(value, field_type)
value = tostring(value)
if field_type == "day" or field_type == "month" then
return value == "00" or
string.match(value, "^0[0-9][0-9]$") ~= nil or
string.match(value, "^0[1-9][0-9]") ~= nil
end
if field_type == "hour" or field_type == "minute" or field_type == "second" then
if value == "00" or string.match(value, "^0[1-9]$") then
return false
end
return string.match(value, "^0[0-9][0-9]+$") ~= nil
end
return false
end
--- Comprova si el valor és un enter.
local function is_integer(value)
if not value then
return false
end
local num_value = tonumber(value)
if not num_value then
return false
end
if math.floor(num_value) ~= num_value then
return false
end
if type(value) == "string" then
if string.find(value, "%.") then
return false
end
end
return true
end
--- Retorna el nom del mes a partir del seu número.
local function get_month_name(month_number)
month_number = tonumber(month_number)
return MONTHS[month_number]
end
--- Funció per determinar si s'ha d'apostrofar la preposició davant del mes.
-- S'apostrofen els mesos que comencen per vocal: abril, agost, octubre.
local function get_month_preposition(month_name)
if not month_name then return "" end
local primera_lletra = string.sub(month_name, 1, 1)
if primera_lletra == "a" or primera_lletra == "o" then
return "d'"
else
return "de "
end
end
--- Genera un missatge d'error HTML.
local function generate_error(message, add_tracking_category)
local category = ERROR_CATEGORY
if add_tracking_category == false then
category = ""
end
local article_title = mw.title.getCurrentTitle()
local is_test_page = article_title.subpageText == "testcases"
local allow_this_test_page = article_title.fullText == "Module talk:Date time/testcases"
if (not CATEGORY_NAMESPACES[article_title.namespace] and not allow_this_test_page)
or (is_test_page and not allow_this_test_page) then
category = ""
end
return '<strong class="error">Error: ' .. message .. '</strong> ' .. help_link .. category
end
--------------------------
-- Funcions de Format --
--------------------------
--- Formata la part de l'hora.
local function format_time_string(hour, minute, second)
if not hour then
return ""
end
local time_string = string.format("%s:%s", hour, minute)
if second and second ~= "00" and minute ~= "00" then
time_string = string.format("%s:%s", time_string, second)
end
-- En català sol separar-se l'hora del text amb un espai normal, no amb coma.
return time_string .. "," .. HTML_SPACE
end
--- Formata la data en format català aplicant les regles d'apostrofació.
local function format_date_string(year, month, day, date_format_mdy)
if not year then
return ""
end
local date_string
if month then
local month_name = get_month_name(month)
local prep = get_month_preposition(month_name)
if day then
day = tonumber(day)
-- En català el format habitual és sempre Dia de Mes de Any (DMY).
if date_format_mdy then
-- Format americà forçat (poc comú en català)
date_string = month_name .. HTML_NBSP .. day .. "," .. HTML_NBSP .. year
else
-- Format estàndard català: 14 de febrer de 1993 / 5 d'abril de 1993
date_string = day .. HTML_NBSP .. prep .. month_name .. HTML_NBSP .. "de" .. HTML_NBSP .. year
end
else
-- CAS SENSE DIA: {{Data inici|1993|2}}
-- Genera primer "febrer de 1993" o "d'abril de 1993"
date_string = month_name .. HTML_NBSP .. "de" .. HTML_NBSP .. year
-- Apliquem la majúscula inicial només a la primera lletra per obtenir:
-- "Febrer de 1993" o "D'abril de 1993" segons correspongui
date_string = date_string:gsub("^%a", string.upper)
end
else
date_string = year
end
return date_string
end
--- Formata la zona horària.
local function format_timezone(timezone)
if not timezone then
return ""
end
return HTML_SPACE .. (timezone == "Z" and "(UTC)" or "(" .. timezone .. ")")
end
--- Genera l'estructura hCalendar oculta.
local function generate_h_calendar(date_time_values, classes)
local parts = {}
if date_time_values.year then
table.insert(parts, date_time_values.year)
if date_time_values.month then
table.insert(parts, "-" .. date_time_values.month)
if date_time_values.day then
table.insert(parts, "-" .. date_time_values.day)
end
end
if date_time_values.hour then
table.insert(parts, "T" .. date_time_values.hour)
if date_time_values.minute then
table.insert(parts, ":" .. date_time_values.minute)
if date_time_values.second then
table.insert(parts, ":" .. date_time_values.second)
end
end
end
end
local h_calendar_content = table.concat(parts) .. (date_time_values.timezone or "")
local class_span = string.format('<span class="%s">', classes)
return string.format(
'<span style="display: none;">%s(%s)</span>',
HTML_NBSP,
class_span .. h_calendar_content .. '</span>'
)
end
--- Genera la cadena de text "fa temps" cridant al Module:Time ago en català.
local function get_time_ago(date_time_values, br, p_param)
local timestamp
local min_magnitude
if date_time_values.day then
timestamp = string.format("%d-%02d-%02d",
date_time_values.year,
date_time_values.month,
date_time_values.day)
min_magnitude = "days"
elseif date_time_values.month then
timestamp = string.format("%d-%02d",
date_time_values.year,
date_time_values.month)
local current_date = os.date("*t")
local year_diff = current_date.year - date_time_values.year
local month_diff = (year_diff * 12) + (current_date.month - date_time_values.month)
if month_diff < 12 then
min_magnitude = "months"
else
min_magnitude = "years"
end
else
timestamp = tostring(date_time_values.year)
min_magnitude = "years"
end
-- Crida al mòdul de temps passat (que ja ha d'estar en català segons el pas anterior)
local m_time_ago = require("Module:Time ago")._main
local time_ago = m_time_ago({timestamp, ["min_magnitude"] = min_magnitude})
if br then
time_ago = p_param and ("<br/>(" .. time_ago .. ")") or (";<br/>" .. time_ago)
else
time_ago = p_param and (HTML_SPACE .. "(" .. time_ago .. ")") or (";" .. HTML_SPACE .. time_ago)
end
return "<span class=\"noprint\">" .. time_ago .. "</span>"
end
-------------------------
-- Funcions de Validació --
-------------------------
local function _validate_date_time(args)
local template_name = args.template or "start date"
help_link = string.format("<small>[[:Template:%s|(ajuda)]]</small>", template_name)
local date_time_values = {
year = args[1],
month = args[2],
day = args[3],
hour = args[4],
minute = args[5],
second = args[6]
}
for key, value in pairs(date_time_values) do
if value then
if not is_integer(value) then
return generate_error(ERROR_MESSAGES.integers)
end
if has_leading_zeros(tostring(value), key) then
return generate_error(ERROR_MESSAGES.has_leading_zeros)
end
date_time_values[key] = tonumber(value)
end
end
if not date_time_values.year then
return generate_error(ERROR_MESSAGES.missing_year)
end
if date_time_values.month and (date_time_values.month < 1 or date_time_values.month > 12) then
return generate_error(ERROR_MESSAGES.invalid_month)
end
if date_time_values.day then
if not date_time_values.month then
return generate_error(ERROR_MESSAGES.missing_month)
end
local max_day = get_days_in_month(date_time_values.year, date_time_values.month)
if date_time_values.day < 1 or date_time_values.day > max_day then
return generate_error(string.format(ERROR_MESSAGES.invalid_day, date_time_values.month, max_day))
end
end
if (date_time_values.minute or date_time_values.second) and not date_time_values.hour then
return generate_error(ERROR_MESSAGES.time_without_hour)
end
if date_time_values.hour and (date_time_values.hour < 0 or date_time_values.hour > 23) then
return generate_error(ERROR_MESSAGES.invalid_hour)
end
if date_time_values.minute and (date_time_values.minute < 0 or date_time_values.minute > 59) then
return generate_error(ERROR_MESSAGES.invalid_minute)
end
if date_time_values.second and (date_time_values.second < 0 or date_time_values.second > 59) then
return generate_error(ERROR_MESSAGES.invalid_second)
end
if args[7] and not (date_time_values.day and date_time_values.hour) then
return generate_error(ERROR_MESSAGES.timezone_incomplete_date)
elseif args[7] and not is_timezone_valid(args[7]) then
return generate_error(ERROR_MESSAGES.invalid_timezone)
end
if args.p and args.paren then
return generate_error(string.format(ERROR_MESSAGES.duplicate_parameters, "p", "paren"))
end
local boolean_params = {'df', 'p', 'paren', 'br'}
for _, param_name in ipairs(boolean_params) do
if args[param_name] and not (args[param_name] == "yes" or args[param_name] == "y") then
return generate_error(string.format(ERROR_MESSAGES.yes_value_parameter, param_name))
end
end
return nil
end
----------------------
-- Funcions Públiques --
----------------------
function p.validate_date_time(frame)
local get_args = require("Module:Arguments").getArgs
local args = get_args(frame)
args[7] = fix_timezone(args[7])
return _validate_date_time(args)
end
function p.generate_date(frame)
local get_args = require("Module:Arguments").getArgs
local args = get_args(frame)
args[7] = fix_timezone(args[7])
local validation_error = _validate_date_time(args)
if validation_error then
return validation_error
end
local classes = TEMPLATE_CLASSES[args.template or "start date"]
if not classes then
return generate_error(ERROR_MESSAGES.template, false)
end
local date_time_values = {
year = args[1],
month = pad_left_zeros(args[2]),
day = pad_left_zeros(args[3]),
hour = pad_left_zeros(args[4]),
minute = args[5] and pad_left_zeros(args[5]) or "00",
second = args[6] and pad_left_zeros(args[6]) or "00",
timezone = replace_minus_character(args[7], true)
}
local time_string = format_time_string(
date_time_values.hour,
date_time_values.minute,
date_time_values.second
)
-- Invertim el paràmetre 'df' perquè en català el comportament per defecte ha de ser DMY (12 de març de 2026).
local date_string = format_date_string(
date_time_values.year,
date_time_values.month,
date_time_values.day,
args.df == "yes" or args.df == "y" -- Si es passa df=yes es forçarà l'estil americà, altrament farà el català nativament
)
local timezone_string = format_timezone(date_time_values.timezone)
local time_ago = ""
if TIME_AGO[args.template] then
time_ago = get_time_ago(
date_time_values,
args.br,
args.p or args.paren
)
end
local h_calendar = generate_h_calendar(date_time_values, classes)
return time_string .. date_string .. timezone_string .. time_ago .. h_calendar
end
return p