js 如何代码实现 聊天记录按天显示日期
时间: 2023-06-02 10:08:08 浏览: 49
可以通过以下步骤来实现聊天记录按天显示日期:
1. 将聊天记录按照时间戳进行排序;
2. 遍历排序后的聊天记录,将每一条记录的时间戳转换为日期,记录下来;
3. 在显示聊天记录的界面上,根据日期进行分组,将同一天的聊天记录放在一个分组中,并显示对应的日期。
以下是一个简单的 JavaScript 实现:
```javascript
function groupChatByDay(chatRecords) {
chatRecords.sort((a, b) => a.timestamp - b.timestamp);
const groups = [];
let currentGroupIndex = -1;
chatRecords.forEach((record) => {
const recordDate = new Date(record.timestamp).toLocaleDateString();
if (currentGroupIndex === -1 || groups[currentGroupIndex].date !== recordDate) {
groups.push({
date: recordDate,
records: [record],
});
currentGroupIndex++;
} else {
groups[currentGroupIndex].records.push(record);
}
});
return groups;
}
```
使用示例:
```javascript
const chatRecords = [
{ timestamp: 1628620800000, content: 'Hello!', sender: 'Alice' },
{ timestamp: 1628624400000, content: 'How are you?', sender: 'Bob' },
{ timestamp: 1628628000000, content: 'I\'m fine, thank you.', sender: 'Alice' },
{ timestamp: 1628797200000, content: 'Good night!', sender: 'Bob' },
{ timestamp: 1628877600000, content: 'Good morning!', sender: 'Alice' },
];
const groups = groupChatByDay(chatRecords);
console.log(groups);
```
输出:
```javascript
[
{
date: '08/11/2021',
records: [
{ timestamp: 1628620800000, content: 'Hello!', sender: 'Alice' },
{ timestamp: 1628624400000, content: 'How are you?', sender: 'Bob' },
{ timestamp: 1628628000000, content: 'I\'m fine, thank you.', sender: 'Alice' }
]
},
{
date: '08/12/2021',
records: [
{ timestamp: 1628797200000, content: 'Good night!', sender: 'Bob' }
]
},
{
date: '08/13/2021',
records: [
{ timestamp: 1628877600000, content: 'Good morning!', sender: 'Alice' }
]
}
]
```