tiefen_space_app/utils/formatTimestamp.js

43 lines
1.0 KiB
JavaScript

export default function formatTimestamp(timestamp) {
const now = new Date();
const date = new Date(timestamp * 1000);
// 检查是否是今天
if (now.toDateString() === date.toDateString()) {
return date.toLocaleTimeString(undefined, {
hour: "numeric",
minute: "numeric",
});
}
// 获取昨天的日期
const yesterday = new Date(now);
yesterday.setDate(now.getDate() - 1);
// 检查是否是昨天
if (yesterday.toDateString() === date.toDateString()) {
return `昨天 ${date.getHours()}:${String(date.getMinutes()).padStart(
2,
"0"
)}`;
}
// 检查是否是今年
if (now.getFullYear() === date.getFullYear()) {
return `${
date.getMonth() + 1
}-${date.getDate()} ${date.getHours()}:${String(date.getMinutes()).padStart(
2,
"0"
)}`;
}
// 不是今年,返回完整日期和时间
return `${date.getFullYear()}-${
date.getMonth() + 1
}-${date.getDate()} ${date.getHours()}:${String(date.getMinutes()).padStart(
2,
"0"
)}`;
}