import { i18next } from '@tencentcloud/uikit-base-component-react'; import { format, isSameWeek, isThisYear, isToday, isYesterday, } from 'date-fns'; import { zhCN, ja, ko, zhTW, enUS } from 'date-fns/locale'; function getTimeStamp(time: number, language = 'en-US') { const locales: any = { 'zh-CN': zhCN, 'zh-TW': zhTW, 'en-US': enUS, 'ja-JP': ja, 'ko-KR': ko, }; const isZh = language.startsWith('zh'); const locale = locales[language] || locales['en-US']; const timeFormat = 'HH:mm'; if (!time) { return ''; } if (isToday(time)) { return format(time, timeFormat, { locale }); } if (isYesterday(time)) { const yesterdayText = i18next.t('TUIChat.Yesterday', { defaultValue: 'Yesterday' }); return `${yesterdayText} ${format(time, timeFormat, { locale })}`; } if (isSameWeek(time, new Date(), { weekStartsOn: 1 })) { return `${format(time, 'EEEE', { locale })} ${format(time, timeFormat, { locale })}`; } if (isThisYear(time)) { if (isZh) { return format(time, 'M月d日 HH:mm', { locale }); } return format(time, 'MMMM d HH:mm', { locale }); } if (isZh) { return format(time, 'yyyy年M月d日 HH:mm', { locale }); } return format(time, 'yyyy/MM/dd HH:mm', { locale }); } const birthdayToAge = (birthday: number) => { const today = new Date(); const birthDate = new Date( Math.floor(birthday / 10000), Math.floor((birthday % 10000) / 100) - 1, birthday % 100, ); let age = today.getFullYear() - birthDate.getFullYear(); const monthDiff = today.getMonth() - birthDate.getMonth(); if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) { age -= 1; } return age; }; const ageToBirthday = (age: number | undefined) => { if (!age) { return undefined; } const today = new Date(); const year = today.getFullYear() - age; return year * 10000 + (today.getMonth() + 1) * 100 + today.getDate(); }; export { getTimeStamp, birthdayToAge, ageToBirthday, };