diff --git a/src/utils/datetime.ts b/src/utils/datetime.ts index f69acad4..b2a4a434 100644 --- a/src/utils/datetime.ts +++ b/src/utils/datetime.ts @@ -16,18 +16,7 @@ export function dateFormatJS(opts: { monthStyle?: 'numeric' | '2-digit' | 'long' | 'short'; timeStyle?: 'full' | 'long' | 'medium' | 'short'; }) { - const dateObject = opts.date ? new Date(opts.date) : new Date(); - - const dateFormat = new Date( - Date.UTC( - dateObject.getUTCFullYear(), - dateObject.getUTCMonth(), - dateObject.getUTCDate(), - dateObject.getUTCHours(), - dateObject.getUTCMinutes(), - dateObject.getUTCSeconds(), - ), - ); + const dt = opts.date ? new Date(opts.date) : new Date(); const { locale } = i18n.global; @@ -35,20 +24,21 @@ export function dateFormatJS(opts: { opts.locale = locale.value === Lang.Thai ? 'th-Th' : 'en-US'; } - let formattedDate = new Intl.DateTimeFormat(opts.locale, { + let formatted = new Intl.DateTimeFormat(opts.locale, { day: opts.dayStyle || 'numeric', month: opts.monthStyle || 'short', timeStyle: opts.timeStyle, year: 'numeric', - }).format(dateFormat); + }).format(dt); - if (opts.locale === 'th-Th') { - formattedDate = formattedDate.replace(/(\d{4})/, (year) => - (parseInt(year) - 543).toString(), - ); + switch (opts.locale) { + case 'th-Th': + return formatted.replace(/(\d{4})/, (year) => + (parseInt(year) - 543).toString(), + ); + default: + return formatted; } - - return formattedDate; } /** @@ -67,10 +57,7 @@ export function dateFormat( if (!m.isValid()) return ''; if (time) return m.format('HH:mm'); - if (number) { - const formattedNumberDate = m.format('L'); - return formattedNumberDate; - } + if (number) return m.format('L'); const monthFormat = fullmonth ? 'MMMM' : 'MMM'; const formattedDate = m.format( @@ -107,25 +94,22 @@ export function toISOStringWithTimezone(date: Date) { ); } -export function calculateAge(birthDate: Date | null | string): string; +export function calculateAge(dt: Date | null | string): string; export function calculateAge( - birthDate: Date | null | string, + dt: Date | null | string, only: 'year' | 'months' | 'days', ): number; export function calculateAge( - birthDate: Date | null | string, + dt: Date | null | string, only?: 'year' | 'months' | 'days', ) { - if (!birthDate) return null; + if (!dt) return null; - const birthDateTimeStamp = new Date(birthDate).getTime(); - const now = new Date(); - const diff = now.getTime() - birthDateTimeStamp; - - const ageDate = new Date(diff); - const years = ageDate.getUTCFullYear() - 1970; - const months = ageDate.getUTCMonth(); - const days = ageDate.getUTCDate() - 1; + const diff = Date.now() - new Date(dt).getTime(); + const offset = new Date(diff); + const years = offset.getUTCFullYear() - 1970; + const months = offset.getUTCMonth(); + const days = offset.getUTCDate() - 1; switch (only) { case 'year':