const formatPast = (date, type = "default", zeroFillFlag = true) => {
const getTimeDifference = (current, past) => Math.floor((current - past) / 1000);
const formatDate = (date, separator = "", zeroFill = true) => {
const year = date.getFullYear();
const month = zeroFill ? String(date.getMonth() + 1).padStart(2, "0") : date.getMonth() + 1;
const day = zeroFill ? String(date.getDate()).padStart(2, "0") : date.getDate();
return ${year}${separator}${month}${separator}${day}
;
};
const timeDifference = getTimeDifference(new Date(), new Date(date));
if (timeDifference < 10) {
return "刚刚";
} else if (timeDifference < 60) {
return ${timeDifference}秒前
;
} else if (timeDifference < 3600) {
return ${Math.floor(timeDifference / 60)}分钟前
;
} else if (timeDifference < 86400) {
return ${Math.floor(timeDifference / 3600)}小时前
;
} else if (timeDifference >= 86400 && type === "default") {
const daysDifference = Math.floor(timeDifference / 86400);
if (daysDifference >= 365) {
return ${Math.floor(daysDifference / 365)}年前
;
} else if (daysDifference >= 30) {
return ${Math.floor(daysDifference / 30)}个月前
;
} else {
return ${daysDifference}天前
;
}
} else {
const formattedDate = formatDate(new Date(date), type === "年月日" ? "年月日" : type);
return zeroFillFlag ? formattedDate : formattedDate.replace(/^[0]+/g, "");
}
};
console.log(formatPast("2024-1-1 11:11:11")); // 3天前
console.log(formatPast("2023-11-1 11:11:11")); // 2个月前
console.log(formatPast("2015-07-10 21:32:01")); // 8年前
console.log(formatPast("2023-02-01 09:32:01", "-", false)); // 2023-2-1
console.log(formatPast("2023.12.8 19:32:01", "/")); // 2023/12/08
console.log(formatPast("2023.12.8 19:32:01", ".")); // 2023.12.08
console.log(formatPast("2023/5/10 11:32:01", "年月日")); // 2023年05月10日
console.log(formatPast("2023/6/25 11:32:01", "月日", false)); // 6月25日
console.log(formatPast("2023/8/08 11:32:01", "年")); // 2023年