参数相关
date为传入时间
例:"2023/5/10 11:32:01" 2023-02-01 09:32:01type为返回类型
例:- / 年月日 年默认规则,大于等于一天(24小时)展示'X天前;大于等于30天且小于365天展示'X个月前';大于等于365天且展示'x年前',否则按照传入参数规则展示
zeroFillFlag参数
为是否数字补零,默认补零
时间参数date为必写参数
时间处理公式依据
- 10秒: 10 * 1000
- 1分钟: 60 * 1000
- 1小时: 60 * 60 * 1000
- 24小时(一天):60 * 60 * 24 * 1000
代码实现
const formatPast = (date, type = "default", zeroFillFlag = true) => {
let countTime;
let time = new Date().getTime();
let afferentTime = new Date(date).getTime();
time = Number.parseInt(`${time - afferentTime}`);
if (time < 10000) {
return "刚刚";
} else if (time < 60000) {
countTime = Math.floor(time / 1000);
return `${countTime}秒前`;
} else if (time < 3600000) {
countTime = Math.floor(time / 60000);
return `${countTime}分钟前`;
} else if (time < 86400000) {
countTime = Math.floor(time / 3600000);
return `${countTime}小时前`;
} else if (time >= 86400000 && type == "default") {
countTime = Math.floor(time / 86400000);
if (countTime >= 365) {
return `${Math.floor(countTime / 365)}年前`;
}
if (countTime >= 30) {
return `${Math.floor(countTime / 30)}个月前`;
}
return `${countTime}天前`;
} else {
let Y = new Date(date).getFullYear();
let M = new Date(date).getMonth() + 1;
let zeroFillM = M > 9 ? M : "0" + M;
let D = new Date(date).getDate();
let zeroFillD = D > 9 ? D : "0" + D;
if (type == "-" || type == "/" || type == ".") {
return zeroFillFlag
? Y + type + zeroFillM + type + zeroFillD
: Y + type + M + type + D;
}
if (type == "年月日") {
return zeroFillFlag
? Y + type[0] + zeroFillM + type[1] + zeroFillD + type[2]
: Y + type[0] + M + type[1] + D + type[2];
}
if (type == "月日") {
return zeroFillFlag
? zeroFillM + type[0] + zeroFillD + type[1]
: M + type[0] + D + type[1]
}
if (type == "年") {
return Y + type
}
}
};
console.log(formatPast("2024-1-1 11:11:11"));
console.log(formatPast("2023-11-1 11:11:11"));
console.log(formatPast("2015-07-10 21:32:01"));
console.log(formatPast("2023-02-01 09:32:01", "-", false));
console.log(formatPast("2023.12.8 19:32:01", "/"));
console.log(formatPast("2023.12.8 19:32:01", "."));
console.log(formatPast("2023/5/10 11:32:01", "年月日"));
console.log(formatPast("2023/6/25 11:32:01", "月日", false));
console.log(formatPast("2023/8/08 11:32:01", "年"));