Files
devbox/js/tools-time.js
T
2026-11-17 14:51:40 +08:00

293 lines
15 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* DevBox · 时间工具:时间戳 / 日期计算 / Cron */
(function () {
'use strict'
const { el, panelTitle, copy, toast, onInput } = DB
const pane = (title, right) => { const p = el('div', { class: 'panel' }); if (title) p.append(panelTitle(title, right)); return p }
const btn = (label, fn, cls = '') => el('button', { class: 'btn ' + cls, text: label, onclick: fn })
const rowKV = (pairs) => {
const dl = el('dl', { class: 'kv' })
for (const [k, v, copyable] of pairs) {
dl.append(el('dt', { text: k }), el('dd', {}, el('span', { text: v }),
copyable === false ? null : el('button', { class: 'btn tiny', style: { marginLeft: '8px' }, text: '复制', onclick: () => copy(String(v)) })))
}
return dl
}
const pad = (n) => String(n).padStart(2, '0')
const fmtLocal = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
const fmtUTC = (d) => `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())} ${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}:${pad(d.getUTCSeconds())}`
const tzOffset = () => {
const off = -new Date().getTimezoneOffset()
const s = off >= 0 ? '+' : '-'
return 'UTC' + s + pad(Math.floor(Math.abs(off) / 60)) + ':' + pad(Math.abs(off) % 60)
}
function relative(d) {
const diff = (d.getTime() - Date.now()) / 1000
const a = Math.abs(diff)
const unit = a < 60 ? [Math.round(a), '秒'] : a < 3600 ? [Math.round(a / 60), '分钟'] : a < 86400 ? [Math.round(a / 3600), '小时'] : a < 2592000 ? [Math.round(a / 86400), '天'] : a < 31536000 ? [Math.round(a / 2592000), '个月'] : [Math.round(a / 31536000), '年']
return diff >= 0 ? `${unit[0]} ${unit[1]}后` : `${unit[0]} ${unit[1]}前`
}
/* ================= 时间戳 ================= */
DB.tool({
id: 'timestamp',
name: '时间戳转换',
group: 'time',
icon: 'clock',
desc: '秒 / 毫秒自动识别,同时给出本地、UTC、ISO 与相对时间',
keywords: ['timestamp', 'unix', 'epoch', '时间戳', '日期', '转换', 'iso'],
mount(root) {
const input = el('input', { type: 'text', value: String(Math.floor(Date.now() / 1000)), placeholder: '1730000000 / 2024-10-27 12:00:00', spellcheck: 'false' })
const out = el('div', {}, rowKV([['时间', '—']]))
const note = el('div', { class: 'hint' })
const nowLine = el('div', { class: 'hint' })
const parse = (raw) => {
const s = raw.trim()
if (!s) return null
if (/^\d{13}$/.test(s)) return new Date(Number(s))
if (/^\d{10}$/.test(s)) return new Date(Number(s) * 1000)
if (/^\d+$/.test(s)) return new Date(Number(s.length > 12 ? Number(s) / 1000 : s) * 1000)
const norm = s.replace(/\//g, '-').replace(' ', 'T')
const d = new Date(norm)
if (!isNaN(d)) return d
const d2 = new Date(s)
return isNaN(d2) ? null : d2
}
const run = () => {
const d = parse(input.value)
out.textContent = ''
if (!d) { note.textContent = '看不懂这个时间,试试 10 位/13 位数字,或 2024-10-27 12:00:00'; return }
note.textContent = ''
const ms = d.getTime()
out.append(rowKV([
['本地时间', fmtLocal(d) + '(' + tzOffset() + ')'],
['UTC', fmtUTC(d)],
['ISO 8601', d.toISOString()],
['Unix(秒)', String(Math.floor(ms / 1000))],
['Unix(毫秒)', String(ms)],
['相对现在', relative(d)],
['星期', '星期' + '日一二三四五六'[d.getDay()]],
['一年中第', Math.ceil((ms - new Date(d.getFullYear(), 0, 0)) / 86400000) + ' 天'],
]))
}
onInput(input, run, 200)
const live = () => { nowLine.textContent = '现在是 ' + fmtLocal(new Date()) + '(' + tzOffset() + ')· ' + Math.floor(Date.now() / 1000) }
live()
setInterval(live, 1000)
const p1 = pane('输入时间', btn('填入现在', () => { input.value = String(Math.floor(Date.now() / 1000)); run() }))
p1.append(input, el('div', { class: 'row', style: { marginTop: '10px' } },
btn('当前秒', () => { input.value = String(Math.floor(Date.now() / 1000)); run() }),
btn('当前毫秒', () => { input.value = String(Date.now()); run() }),
btn('今天 0 点', () => { const d = new Date(); d.setHours(0, 0, 0, 0); input.value = String(Math.floor(d.getTime() / 1000)); run() }),
btn('+1 小时', () => { const d = parse(input.value) || new Date(); input.value = String(Math.floor(d.getTime() / 1000) + 3600); run() })))
const p2 = pane('结果')
p2.append(out, note, nowLine)
root.append(p1, p2)
run()
},
})
/* ================= 日期计算 ================= */
DB.tool({
id: 'date',
name: '日期计算',
group: 'time',
icon: 'calendar',
desc: '日期加减、两日期相差多少天、工作日推算',
keywords: ['date', 'days', 'between', '日期', '相差', '加减', '工作日'],
mount(root) {
const toLocal = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
const start = el('input', { type: 'date', value: toLocal(new Date()) })
const amount = el('input', { type: 'number', value: 7 })
const unit = el('select', {}, ...[['day', '天'], ['week', '周'], ['month', '月'], ['year', '年'], ['workday', '工作日']].map(([v, t]) => el('option', { value: v, text: t })))
const res = el('div', {})
const addRun = () => {
const d = new Date(start.value + 'T00:00:00')
if (isNaN(d)) { res.textContent = '先选一个日期'; return }
const n = Number(amount.value) || 0
const r = new Date(d)
if (unit.value === 'day') r.setDate(r.getDate() + n)
else if (unit.value === 'week') r.setDate(r.getDate() + n * 7)
else if (unit.value === 'month') r.setMonth(r.getMonth() + n)
else if (unit.value === 'year') r.setFullYear(r.getFullYear() + n)
else {
let left = Math.abs(n), dir = n >= 0 ? 1 : -1
while (left > 0) { r.setDate(r.getDate() + dir); const w = r.getDay(); if (w !== 0 && w !== 6) left-- }
}
res.textContent = ''
res.append(rowKV([['结果', fmtLocal(r).slice(0, 10) + ' 星期' + '日一二三四五六'[r.getDay()]], ['距今', relative(r)]]))
}
;[start, amount, unit].forEach((n) => n.addEventListener('change', addRun))
const d1 = el('input', { type: 'date', value: toLocal(new Date()) })
const d2 = el('input', { type: 'date', value: toLocal(new Date(Date.now() + 86400000 * 30)) })
const diffOut = el('div', {})
const diffRun = () => {
const a = new Date(d1.value + 'T00:00:00'), b = new Date(d2.value + 'T00:00:00')
if (isNaN(a) || isNaN(b)) return
const days = Math.round((b - a) / 86400000)
let workdays = 0
const s = new Date(Math.min(a, b)), e = new Date(Math.max(a, b))
for (const t = new Date(s); t < e; t.setDate(t.getDate() + 1)) { const w = t.getDay(); if (w !== 0 && w !== 6) workdays++ }
diffOut.textContent = ''
diffOut.append(rowKV([
['相差', Math.abs(days) + ' 天'],
['约合', (Math.abs(days) / 7).toFixed(1) + ' 周 · ' + (Math.abs(days) / 30.44).toFixed(1) + ' 个月'],
['工作日', workdays + ' 天'],
['顺序', days === 0 ? '同一天' : days > 0 ? '第二个更晚' : '第一个更晚'],
]))
}
;[d1, d2].forEach((n) => n.addEventListener('change', diffRun))
const p1 = pane('日期加减')
p1.append(el('div', { class: 'row' }, el('div', { style: { flex: '1 1 180px' } }, start), el('div', { style: { width: '110px' } }, amount), el('div', { style: { width: '130px' } }, unit)), el('div', { style: { marginTop: '12px' } }, res))
const p2 = pane('两个日期相差')
p2.append(el('div', { class: 'grid2' }, el('label', { class: 'field' }, el('span', { text: '开始' }), d1), el('label', { class: 'field' }, el('span', { text: '结束' }), d2)), el('div', { style: { marginTop: '12px' } }, diffOut))
root.append(p1, p2)
addRun(); diffRun()
},
})
/* ================= Cron ================= */
DB.tool({
id: 'cron',
name: 'Cron 表达式',
group: 'time',
icon: 'bolt',
desc: '解释 5/6 段 cron 的含义,并算出接下来 5 次执行时间',
keywords: ['cron', 'crontab', 'schedule', '定时', '表达式'],
mount(root) {
const input = el('input', { type: 'text', value: '*/15 9-18 * * 1-5', spellcheck: 'false', style: { fontFamily: 'var(--mono)' } })
const out = el('div', { class: 'stack' })
const err = el('div', { class: 'err' })
const presets = [
['每 5 分钟', '*/5 * * * *'],
['每小时整点', '0 * * * *'],
['每天 9:00', '0 9 * * *'],
['工作日 9-18 每 15 分', '*/15 9-18 * * 1-5'],
['每周一 8:30', '30 8 * * 1'],
['每月 1 号 0 点', '0 0 1 * *'],
]
const parseField = (text, min, max) => {
const set = new Set()
for (const part of text.split(',')) {
let step = 1, range = part
if (part.includes('/')) { const [r, s] = part.split('/'); range = r; step = Number(s) }
let from = min, to = max
if (range !== '*') {
if (range.includes('-')) { const [a, b] = range.split('-'); from = Number(a); to = Number(b) }
else from = to = Number(range)
}
if (!Number.isInteger(from) || !Number.isInteger(to) || from < min || to > max || from > to || step <= 0) throw new Error(`字段 "${text}" 超出范围 ${min}-${max}`)
for (let v = from; v <= to; v += step) set.add(v)
}
return set
}
const DAYS = '日一二三四五六'
const sorted = (set) => [...set].sort((a, b) => a - b)
const isAll = (set, min, max) => set.size === max - min + 1
const stepOf = (set) => {
const v = sorted(set)
if (v.length < 2) return 0
const d = v[1] - v[0]
for (let i = 2; i < v.length; i++) if (v[i] - v[i - 1] !== d) return 0
return d > 1 ? d : 0
}
const contiguous = (set) => { const v = sorted(set); return v.length > 1 && v[v.length - 1] - v[0] === v.length - 1 }
const hhmm = (h, m) => pad(h) + ':' + pad(m)
const describe = (f) => {
const [mi, ho, dom, mo, dow] = f
const parts = []
// 日期条件
if (!isAll(dow, 0, 6)) {
const v = sorted(dow)
if (contiguous(dow)) parts.push(`周${DAYS[v[0]]}至周${DAYS[v[v.length - 1]]}`)
else if (v.length === 1) parts.push(`周${DAYS[v[0]]}`)
else parts.push(v.map((d) => '周' + DAYS[d]).join('、'))
}
if (!isAll(dom, 1, 31)) {
const v = sorted(dom)
parts.push(contiguous(dom) ? `每月 ${v[0]}–${v[v.length - 1]} 号` : `每月 ${v.join('、')} 号`)
}
if (!isAll(mo, 1, 12)) parts.push(sorted(mo).join('、') + ' 月')
// 时间部分
const mStep = stepOf(mi), hStep = stepOf(ho)
const oneMin = mi.size === 1, oneHour = ho.size === 1
const hAll = isAll(ho, 0, 23), mAll = isAll(mi, 0, 59)
const hRange = ho.size > 1 && contiguous(ho)
const mRange = mi.size > 1 && contiguous(mi)
let t
if (mAll && hAll) t = '每分钟'
else if (mAll) t = hRange ? `${pad(sorted(ho)[0])}:00–${pad(sorted(ho).slice(-1)[0])}:59 每分钟` : `每小时的每分钟`
else if (mStep && hAll) t = `每 ${mStep} 分钟`
else if (oneMin && hAll) t = `每小时的第 ${sorted(mi)[0]} 分`
else if (oneMin && oneHour) t = `每天 ${hhmm(sorted(ho)[0], sorted(mi)[0])}`
else if (oneMin && hRange) t = `${hhmm(sorted(ho)[0], sorted(mi)[0])} 到 ${hhmm(sorted(ho).slice(-1)[0], sorted(mi)[0])} 之间每小时的 :${pad(sorted(mi)[0])}`
else if (mStep && hRange) t = `${pad(sorted(ho)[0])}:00–${pad(sorted(ho).slice(-1)[0])}:59 之间每 ${mStep} 分钟`
else if (hStep && mAll) t = `每 ${hStep} 小时每分钟`
else if (oneMin) t = `每天的 ${sorted(ho).map((h) => hhmm(h, sorted(mi)[0])).join('、')}`
else if (oneHour) t = `每小时的第 ${sorted(mi).map(pad).join('、')} 分`
else t = `${sorted(ho).map(pad).join('、')} 点的 ${sorted(mi).map(pad).join('、')} 分`
parts.push(t)
return parts.join(',')
}
const nextRuns = (f, count = 5) => {
const [mi, ho, dom, mo, dow] = f
const res = []
const start = new Date()
start.setSeconds(0, 0)
const cur = new Date(start.getTime() + 60000)
const limit = new Date(start.getTime() + 366 * 4 * 86400000)
const domRestricted = dom.size !== 31, dowRestricted = dow.size !== 7
while (res.length < count && cur < limit) {
const dayOk = mo.has(cur.getMonth() + 1) && (
domRestricted && dowRestricted ? (dom.has(cur.getDate()) || dow.has(cur.getDay()))
: domRestricted ? dom.has(cur.getDate())
: dowRestricted ? dow.has(cur.getDay()) : true)
if (!dayOk) { cur.setDate(cur.getDate() + 1); cur.setHours(0, 0, 0, 0); continue }
if (!ho.has(cur.getHours())) { cur.setHours(cur.getHours() + 1, 0, 0, 0); continue }
if (!mi.has(cur.getMinutes())) { cur.setMinutes(cur.getMinutes() + 1, 0, 0); continue }
res.push(new Date(cur.getTime()))
cur.setMinutes(cur.getMinutes() + 1, 0, 0)
}
return res
}
const run = () => {
out.textContent = ''
err.textContent = ''
const parts = input.value.trim().split(/\s+/)
if (parts.length === 6) parts.shift()
if (parts.length !== 5) { err.textContent = '要 5 段(分 时 日 月 周),也接受 6 段(含秒,秒会被忽略)'; return }
try {
const f = [parseField(parts[0], 0, 59), parseField(parts[1], 0, 23), parseField(parts[2], 1, 31), parseField(parts[3], 1, 12), parseField(parts[4], 0, 6)]
const desc = pane('含义')
desc.append(el('div', { class: 'out', text: describe(f) }))
const runs = nextRuns(f)
const next = pane('接下来 ' + runs.length + ' 次')
const dl = el('dl', { class: 'kv' })
runs.forEach((d) => dl.append(el('dt', { text: '·' }), el('dd', { text: fmtLocal(d) + '(' + relative(d) + ')' })))
if (!runs.length) dl.append(el('dt', { text: '' }), el('dd', { text: '未来 4 年内没有匹配时间' }))
next.append(dl)
out.append(desc, next)
} catch (e) { err.textContent = e.message }
}
onInput(input, run, 220)
const p1 = pane('表达式')
p1.append(input, el('div', { class: 'row', style: { marginTop: '10px' } },
...presets.map(([label, expr]) => btn(label, () => { input.value = expr; run() }, 'ghost'))))
root.append(p1, err, out)
run()
},
})
})()