// https://github.com/TencentCloud/chat-uikit-vue/tree/main
const handleItemTime = (currTime: number, prevTime: number) => {
// timestampShowFlag.value = false;
if (currTime <= 0) {
return "";
} else if (!prevTime || prevTime <= 0) {
// timestampShowFlag.value = true;
return calculateTimestamp(currTime * 1000);
} else {
const minDiffToShow = 10 * 60; //10min 10:60s
const diff = currTime - prevTime;
if (diff >= minDiffToShow) {
// timestampShowFlag.value = true;
return calculateTimestamp(currTime * 1000);
}
}
return "";
};
/**
* @description 计算时间戳函数 calculate timestamp
* @param timestamp 13位
* @returns
*/
export const calculateTimestamp = (timestamp: number): string => {
const todayZero = new Date().setHours(0, 0, 0, 0);
const thisYear = new Date(new Date().getFullYear(), 0, 1, 0, 0, 0, 0).getTime();
const target = new Date(timestamp);
const oneDay = 24 * 60 * 60 * 1000;
const oneWeek = 7 * oneDay; // const oneYear = 365 * oneDay;
const diff = todayZero - target.getTime();
function formatNum(num: number): string {
return num < 10 ? `0${num}` : num.toString();
}
if (diff <= 0) {
// 今天,只显示小时:分钟
return `${formatNum(target.getHours())}:${formatNum(target.getMinutes())}`;
}
if (diff <= oneDay) {
// 昨天,显示昨天:小时:分钟
return `昨天 ${formatNum(target.getHours())}:${formatNum(target.getMinutes())}`;
}
if (diff <= oneWeek - oneDay) {
// 一周内,显示工作日小时:分钟
const weekdays = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
const weekday = weekdays[target.getDay()];
return `${weekday} ${formatNum(target.getHours())}:${formatNum(target.getMinutes())}`;
}
if (target.getTime() >= thisYear) {
// 一周以上、年内。显示月/日时:分
return `${target.getMonth() + 1}/${target.getDate()} ${formatNum(target.getHours())}:${formatNum(target.getMinutes())}`;
} // 不在今年内,显示 年/月/日 时:分
return `${target.getFullYear()}/${target.getMonth() + 1}/${target.getDate()} ${formatNum(target.getHours())}:${formatNum(
target.getMinutes()
)}`;
};
const calcula = (timestamp: number) => {
return formatTimeAgo<UseTimeAgoUnitNamesDefault>(dayjs.unix(timestamp).toDate(), {
messages: timeConversion
});
// 下面这种也可以
// return formatTimeAgo(new Date(), {
// messages: timeConversion as UseTimeAgoMessages<UseTimeAgoUnitNamesDefault>
// });
};
// https://github.com/vueuse/vueuse/blob/main/packages/core/useTimeAgo/index.ts
export const timeConversion = {
justNow: "刚刚",
past: (n: string) => {
return n.match(/\d/) ? `${n}之前` : n;
},
future: (n: string): string => {
return n.match(/\d/) ? `${n}之后` : n;
},
month: (n: number, past: any) => {
if (n === 1) {
return past ? "上个月" : "下个月";
}
return `${n}月`;
},
year: (n: number, past: any) => {
if (n === 1) {
return past ? "去年" : "明年";
}
return `${n}年`;
},
day: (n: number, past: any) => {
if (n === 1) {
return past ? "昨天" : "明天";
}
return `${n}天`;
},
week: (n: number, past: any) => {
if (n === 1) {
return past ? "上周" : "下周";
}
return `${n}周`;
},
hour: (n: any) => `${n}小时`,
minute: (n: any) => `${n}分钟`,
second: (n: any) => `${n}秒`,
invalid: ""
};