pgh-common-utils
Version:
A collection of utility functions for TypeScript.
36 lines (35 loc) • 1.23 kB
JavaScript
// 时间格式化
export function formatTime(date, format = 'YYYY-MM-DD HH:mm:ss') {
const d = new Date(date);
const pad = (n) => n.toString().padStart(2, '0');
return format
.replace(/YYYY/g, d.getFullYear().toString())
.replace(/MM/g, pad(d.getMonth() + 1))
.replace(/DD/g, pad(d.getDate()))
.replace(/HH/g, pad(d.getHours()))
.replace(/mm/g, pad(d.getMinutes()))
.replace(/ss/g, pad(d.getSeconds()));
}
// 时间精确比较
export function timeDiff(start, end, unit = 'seconds') {
const startTime = new Date(start).getTime();
const endTime = new Date(end).getTime();
const diff = endTime - startTime;
switch (unit) {
case 'seconds': return Math.floor(diff / 1000);
case 'minutes': return Math.floor(diff / (1000 * 60));
case 'hours': return Math.floor(diff / (1000 * 60 * 60));
case 'days': return Math.floor(diff / (1000 * 60 * 60 * 24));
default: return diff;
}
}
// 时间通用比较
export function compareTime(time1, time2) {
const t1 = new Date(time1).getTime();
const t2 = new Date(time2).getTime();
if (t1 < t2)
return -1;
if (t1 > t2)
return 1;
return 0;
}