描述:以最近的时间间隔来格式化时间。
时间间隔为今天,显示 HH:mm,如 09:20,
时间间隔为 1 天,显示 昨天 HH:mm,如 昨天 09:20,
时间间隔为 2 天,显示 前天 HH:mm,如 昨天 09:20,
时间间隔超过 2 天,不超过一年,显示 MM-DD HH:mm,如 01-01 09:20
时间间隔超过一年,显示 YYYY-MM-DD HH:mm,如 2023-01-01 09:20
装包
npm install dayjs
/**
* @description: 用于将时间格式化
* 一年前:YYYY-MM-DD HH:mm
* 一月前:MM-DD HH:mm
* 一天前:昨天 HH:mm
* 两天前::前天 HH:mm
* 当天:HH:mm
* @param {string} date 传入时间戳,以秒或毫秒为单位
* @return {*}
*/
const oneDaySecondCount = 24 * 60 * 60;
const strArr = ['昨天 ', '前天 '];
export const getRelativeTime = (timestamp) => {
let len = timestamp.toString().length;
if (!([10, 13].includes(len))) {
throw new Error('不是正确的时间戳');
}
// 传入的是秒数还是毫秒数
const isUnix = len === 10;
let dayFn = isUnix ? dayjs.unix : dayjs;
let format = 'HH:mm';
let str = '';
const isBeforeYear = dayFn(timestamp).isBefore(dayjs(), 'year');
const isBeforeMonth = dayFn(timestamp).isBefore(dayjs(), 'month');
const isBeforeDate = dayFn(timestamp).isBefore(dayjs(), 'date');
if (isBeforeYear) {
format = 'YYYY-MM-DD ' + format;
} else if (isBeforeMonth) {
format = 'MM-DD ' + format;
} else if (isBeforeDate) {
// 相差秒数
const rel = dateToStartDate({date: dayjs(), type: 'date', isUnix}) - timestamp;
str = strArr[Math.floor(rel / oneDaySecondCount / (isUnix ? 1 : 1000))] || '';
if (!str) format = 'MM-DD ' + format;
}
return str + dayFn(timestamp).format(format);
};
/**
* @description: 获取传入时间在某一时间段的秒(毫秒)数
* @param {string} date 传入时间
* @return {*}
*/
export const dateToStartDate = ({
date,
type,
isUnix = true,
}) => {
if (isUnix) {
return dayjs(date).startOf(type).unix();
} else {
return dayjs(date).startOf(type).valueOf();
}
};
// 秒数
console.log(getRelativeTime(1681531655)); // 12:07
console.log(getRelativeTime(1681443600)); // 昨天 11:40
console.log(getRelativeTime(1673712000)); // 01-15 00:00
console.log(getRelativeTime(1518781876)); // 2018-02-16 19:51
// 时间戳
console.log(getRelativeTime(1681511655000)); // 06:34
console.log(getRelativeTime(1681443600000)); // 昨天 11:40
console.log(getRelativeTime(1671712000000)); // 2022-12-22 20:26
console.log(getRelativeTime(1511781876000)); // 2017-11-27 19:24