Files
tonePage/tonecn/src/lib/timestampToString.ts
2024-08-30 01:08:44 +08:00

46 lines
1.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
function timestampToString(timestamp: string | number) {
if (timestamp === undefined || timestamp === null) {
throw new Error('Timestamp cannot be undefined or null');
}
const date = new Date(+timestamp);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0'); // getMonth() returns 0-11, so we add 1
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
}
function timestampToRelativeWeekday(timestamp: string | number) {
if (timestamp === undefined || timestamp === null) {
throw new Error('Timestamp cannot be undefined or null');
}
const date = new Date(+timestamp);
const today = new Date();
today.setHours(0, 0, 0, 0); // 设置为今天的零点,以便于比较
// 判断是否为明天
const date0000 = new Date(date);
date0000.setHours(0, 0, 0, 0);
const isTomorrow = date0000.getTime() === today.getTime() + 24 * 60 * 60 * 1000;
const isToday = date0000.getTime() === today.getTime();
// 获取星期几注意JavaScript的getDay()返回值是0周日到6周六
const weekday = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'][date.getDay()];
if (isToday) {
return '今天';
} else if (isTomorrow) {
return '明天';
} else {
return weekday;
}
}
export { timestampToString, timestampToRelativeWeekday }