80 lines
2.3 KiB
TypeScript
80 lines
2.3 KiB
TypeScript
![]() |
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 msgtime = new Date(props.msgtime);
|
||
|
|
||
|
const yesterday = new Date();
|
||
|
yesterday.setDate(yesterday.getDate() - 1);
|
||
|
const dayDiff =
|
||
|
(Date.parse(
|
||
|
`${now.getFullYear()}-${padWith(now.getMonth() + 1)}-${padWith(now.getDate())} 00:00:00`,
|
||
|
) -
|
||
|
new Date(props.msgtime).getTime()) /
|
||
|
(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 (
|
||
|
<div style={{ display: 'flex', justifyContent: 'center' }}>
|
||
|
<div
|
||
|
style={{
|
||
|
background: '#DADADA',
|
||
|
color: '#fff',
|
||
|
padding: '0 8px',
|
||
|
borderRadius: 4,
|
||
|
lineHeight: 1,
|
||
|
height: 26,
|
||
|
display: 'inline-flex',
|
||
|
justifyContent: 'center',
|
||
|
alignItems: 'center',
|
||
|
}}
|
||
|
>
|
||
|
{formatTime()}
|
||
|
</div>
|
||
|
</div>
|
||
|
);
|
||
|
};
|