From 938739e8c260d18769cb3ecf16bc5e2321c01e27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A7=89?= Date: Tue, 24 Oct 2023 06:46:40 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8C=89=E6=97=A5=E6=9C=9F=E5=BD=92=E5=B9=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/chat.js | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/chat.js b/src/chat.js index 1ee0683..659d3dd 100644 --- a/src/chat.js +++ b/src/chat.js @@ -197,6 +197,41 @@ export default class Chat { } } 添加元素(data) { + // 人类可读的时间: 今天,昨天, 空字符串 + function convertTimestampToReadableTime(timestamp) { + const date = new Date(timestamp); + const today = new Date(); + const yesterday = new Date(today); + yesterday.setDate(today.getDate() - 1); + if (date.toDateString() === today.toDateString()) { + return '今天'; + } else if (date.toDateString() === yesterday.toDateString()) { + return '昨天'; + } else { + return ''; + } + } + // 如果上一条日期不等于这一条日期,则添加日期(只计算日期,不计算时间) + if (!this.last || this.last.time.split(' ')[0] !== data.time.split(' ')[0]) { + this.ul.appendChild(ListItem({ + style: { listStyle: 'none', maxWidth: '24rem', textAlign: 'center' }, + children: [ + Span({ + style: { + display: 'inline-block', + padding: '.1rem .5rem', + marginTop: '2rem', + boxSizing: 'border-box', + boxShadow: '0 0 1rem #eee', + borderRadius: '1rem', + fontSize: '12px', + }, + textContent: `${data.time.split(' ')[0]} ${convertTimestampToReadableTime(new Date(data.time).getTime())}` + }) + ] + })) + } + // 如果和上一条消息是同一人, 且时间间隔小于1小时, 则向上合并 // && new Date(time).getTime() - new Date(this.last.time).getTime() < 1000 * 60 * 60 console.log('添加一条消息', this.last, data)