39 lines
1.5 KiB
TypeScript
39 lines
1.5 KiB
TypeScript
export function formatTime(value: string): string {
|
|
return !value || value.startsWith('0001-') ? '—' : new Date(value).toLocaleString('zh-CN')
|
|
}
|
|
|
|
function localInput(d: Date): string {
|
|
return new Date(d.getTime() - d.getTimezoneOffset() * 60000).toISOString().slice(0, 16)
|
|
}
|
|
|
|
export function localToUTC(value: string): string {
|
|
const d = new Date(value)
|
|
if (!/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}$/.test(value) || !Number.isFinite(d.getTime()) || localInput(d) !== value) throw new Error('无效的本地时间。')
|
|
return d.toISOString()
|
|
}
|
|
|
|
export function quickRange(days: number, now = Date.now()) {
|
|
const to = new Date(now), from = new Date(now)
|
|
from.setHours(0, 0, 0, 0)
|
|
from.setDate(from.getDate() - days + 1)
|
|
return { from: from.toISOString(), to: to.toISOString(), fromInput: localInput(from), toInput: localInput(to) }
|
|
}
|
|
|
|
export function filterParams(filter: { key_id: string; from: string; to: string }) {
|
|
const from = filter.from ? localToUTC(filter.from) : ''
|
|
const to = filter.to ? localToUTC(filter.to) : ''
|
|
if (from && to && from > to) throw new Error('开始时间不能晚于结束时间。')
|
|
const params = new URLSearchParams()
|
|
if (filter.key_id) params.set('key_id', filter.key_id)
|
|
if (from) params.set('from', from)
|
|
if (to) params.set('to', to)
|
|
return params
|
|
}
|
|
|
|
export function keyExpiry(value: string, now = Date.now()) {
|
|
if (!value) return ''
|
|
const expires = localToUTC(value)
|
|
if (new Date(expires).getTime() <= now) throw new Error('有效期必须晚于当前时间。')
|
|
return expires
|
|
}
|