From 325334e8490b59f0872c0aa865bf238227bcecff Mon Sep 17 00:00:00 2001 From: tone <3341154833@qq.com> Date: Fri, 30 Aug 2024 01:08:44 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8A=A0=E5=85=A5=E6=97=B6=E9=97=B4=E6=88=B3?= =?UTF-8?q?=E8=BD=AC=E5=AD=97=E7=AC=A6=E4=B8=B2=E5=BA=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tonecn/src/lib/timestampToString.ts | 46 +++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 tonecn/src/lib/timestampToString.ts diff --git a/tonecn/src/lib/timestampToString.ts b/tonecn/src/lib/timestampToString.ts new file mode 100644 index 0000000..28b8c34 --- /dev/null +++ b/tonecn/src/lib/timestampToString.ts @@ -0,0 +1,46 @@ + +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 } \ No newline at end of file