全站通知:
模块:时间进度
刷
历
编
跳到导航
跳到搜索
此模块的文档可以在模块:时间进度/doc创建
local p = {}
-- 内部函数:将“4 12月 2025 00:00:00”转换为标准格式
local function normalizeDate(dateStr)
if not dateStr or dateStr == "" then return "" end
-- 清理空格和修饰符
dateStr = mw.text.trim(dateStr)
-- 匹配格式:(日) (月)月 (年) (时间)
-- 例如:4 12月 2025 00:00:00
local d, m, y, t = mw.ustring.match(dateStr, "(%d+)%s+(%d+)月%s+(%d+)%s*(%d*:%d*:?%d*)")
if d and m and y then
-- 如果没有时间部分,补全 00:00:00
if t == "" then t = "00:00:00" end
-- 拼接成 ISO 标准格式:YYYY-MM-DD HH:MM:SS
return string.format("%s-%s-%s %s", y, m, d, t)
end
-- 如果不匹配特殊格式,直接返回原字符串,交给内置函数处理
return dateStr
end
function p.calculate(frame)
-- 获取并预处理参数
local startTimeStr = normalizeDate(frame.args[1] or "")
local endTimeStr = normalizeDate(frame.args[2] or "")
if startTimeStr == "" or endTimeStr == "" then
return "0"
end
-- 解析时间戳
local status1, startTimestamp = pcall(function()
return mw.getContentLanguage():formatDate("U", startTimeStr)
end)
local status2, endTimestamp = pcall(function()
return mw.getContentLanguage():formatDate("U", endTimeStr)
end)
-- 容错:如果解析还是失败
if not status1 or not status2 or not startTimestamp or not endTimestamp then
return "0"
end
startTimestamp = tonumber(startTimestamp)
endTimestamp = tonumber(endTimestamp)
-- 获取当前服务器时间(注意:os.time() 获取的是服务器 UTC 时间)
local now = os.time()
-- 进度计算
if endTimestamp <= startTimestamp then return "0" end
local progress = (now - startTimestamp) / (endTimestamp - startTimestamp)
progress = math.max(0, math.min(progress, 1))
-- 返回纯数字,供 #expr 使用
return string.format("%.4f", progress)
end
return p

沪公网安备 31011002002714 号