Files
scrm.antd/src/pages/ChatLogs/components/ChatTime.tsx

82 lines
2.4 KiB
TypeScript
Raw Normal View History

2023-04-24 13:43:36 +08:00
import React from 'react';
2023-04-11 15:29:40 +08:00
interface IChatTimeProps {
msgtime: string;
}
export const ChatTime: React.FC<IChatTimeProps> = (props) => {
function padWith(value: string | number) {
return `${value}`.padStart(2, '0');
}
const weekStr = ['日', '一', '二', '三', '四', '五', '六'];
const formatTime = () => {
const now = new Date();
const msgtimeStr = props.msgtime.replace(/-/g, '/');
const msgtime = new Date(msgtimeStr);
2023-04-11 15:29:40 +08:00
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
const dayDiff =
2023-04-12 10:10:16 +08:00
(new Date(
`${now.getFullYear()}/${padWith(now.getMonth() + 1)}/${padWith(now.getDate())} 00:00:00`,
2023-04-12 10:10:16 +08:00
).getTime() -
new Date(msgtimeStr).getTime()) /
2023-04-11 15:29:40 +08:00
(24 * 60 * 60 * 1000) +
1;
if (now.getFullYear() == msgtime.getFullYear()) {
if (
now.getFullYear() == msgtime.getFullYear() &&
now.getMonth() == msgtime.getMonth() &&
now.getDate() == msgtime.getDate()
) {
// 当天
return `${padWith(msgtime.getHours())}:${padWith(msgtime.getMinutes())}`;
} else if (
yesterday.getFullYear() == msgtime.getFullYear() &&
yesterday.getMonth() == msgtime.getMonth() &&
yesterday.getDate() == msgtime.getDate()
) {
// 昨天
return `昨天 ${padWith(msgtime.getHours())}:${padWith(msgtime.getMinutes())}`;
} else if (dayDiff < 7) {
// 星期
return `星期${weekStr[msgtime.getDay()]} ${padWith(msgtime.getHours())}:${padWith(
msgtime.getMinutes(),
)}`;
} else {
// 超过7天
return `${padWith(msgtime.getMonth() + 1)}${padWith(msgtime.getDate())}${padWith(
msgtime.getHours(),
)}:${padWith(msgtime.getMinutes())}`;
}
} else {
// 跨年
return `${msgtime.getFullYear()}${padWith(msgtime.getMonth() + 1)}${padWith(
msgtime.getDate(),
)} ${padWith(msgtime.getHours())}:${padWith(msgtime.getMinutes())}`;
}
};
return (
2023-04-12 10:10:16 +08:00
<div style={{ display: 'flex', justifyContent: 'center', marginBottom: 12 }}>
2023-04-11 15:29:40 +08:00
<div
style={{
background: '#DADADA',
color: '#fff',
padding: '0 8px',
borderRadius: 4,
lineHeight: 1,
2023-04-13 17:36:49 +08:00
height: 24,
2023-04-11 15:29:40 +08:00
display: 'inline-flex',
justifyContent: 'center',
alignItems: 'center',
}}
>
{formatTime()}
</div>
</div>
);
};