访客模块待完成
This commit is contained in:
66
src/utils/time.ts
Normal file
66
src/utils/time.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* 计算两个日期之间相差的天数
|
||||
* @param date1 开始日期
|
||||
* @param date2 结束日期
|
||||
* @returns 相差天数(绝对值)
|
||||
*/
|
||||
export function diffDays(date1: string | Date, date2: string | Date): number {
|
||||
const d1 = new Date(date1);
|
||||
const d2 = new Date(date2);
|
||||
// 转为时间戳并取绝对值
|
||||
const diff = Math.abs(d1.getTime() - d2.getTime());
|
||||
// 一天的毫秒数
|
||||
return Math.floor(diff / (1000 * 60 * 60 * 24));
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化两个时间的差值,自动显示 年/月/天/时/分/秒
|
||||
* @param startTime 开始时间(Date / 时间戳 / 字符串)
|
||||
* @param endTime 结束时间,默认当前时间
|
||||
* @returns 如:2年3个月、15天、2小时30分、50秒
|
||||
*/
|
||||
export function formatTimeDiff(startTime: string | number | Date, endTime: string | number | Date = new Date()): string {
|
||||
const start = new Date(startTime).getTime();
|
||||
const end = new Date(endTime).getTime();
|
||||
|
||||
// 毫秒差值(绝对值)
|
||||
let diff = Math.abs(end - start);
|
||||
if (diff < 1000) return '0秒';
|
||||
|
||||
// 单位定义
|
||||
const second = 1000;
|
||||
const minute = 60 * second;
|
||||
const hour = 60 * minute;
|
||||
const day = 24 * hour;
|
||||
const month = 30 * day; // 粗略按月计算
|
||||
const year = 365 * day;
|
||||
|
||||
// 计算
|
||||
const years = Math.floor(diff / year);
|
||||
diff -= years * year;
|
||||
|
||||
const months = Math.floor(diff / month);
|
||||
diff -= months * month;
|
||||
|
||||
const days = Math.floor(diff / day);
|
||||
diff -= days * day;
|
||||
|
||||
const hours = Math.floor(diff / hour);
|
||||
diff -= hours * hour;
|
||||
|
||||
const minutes = Math.floor(diff / minute);
|
||||
diff -= minutes * minute;
|
||||
|
||||
const seconds = Math.floor(diff / second);
|
||||
|
||||
// 拼接显示
|
||||
const res: string[] = [];
|
||||
if (years > 0) res.push(years + '年');
|
||||
if (months > 0) res.push(months + '个月');
|
||||
if (days > 0) res.push(days + '天');
|
||||
if (hours > 0) res.push(hours + '小时');
|
||||
if (minutes > 0) res.push(minutes + '分钟');
|
||||
if (seconds > 0 && res.length === 0) res.push(seconds + '秒');
|
||||
|
||||
return res.join('');
|
||||
}
|
||||
Reference in New Issue
Block a user