fix: refactors date range handling to use a formatted, reactive approach

This commit is contained in:
riefive
2025-11-17 13:16:01 +07:00
parent d6d1efe61f
commit 4ef0156181
5 changed files with 107 additions and 51 deletions
+59 -36
View File
@@ -1,44 +1,67 @@
const monthsInId = [
'Januari',
'Februari',
'Maret',
'April',
'Mei',
'Juni',
'Juli',
'Agustus',
'September',
'Oktober',
'November',
'Desember',
]
export function getAge(dateString: string, comparedDate?: string): { idFormat: string; extFormat: string } {
const birthDate = new Date(dateString);
const today = new Date();
const birthDate = new Date(dateString)
const today = new Date()
if (comparedDate) {
const comparedDateObj = new Date(comparedDate);
today.setFullYear(comparedDateObj.getFullYear());
today.setMonth(comparedDateObj.getMonth());
today.setDate(comparedDateObj.getDate());
}
if (comparedDate) {
const comparedDateObj = new Date(comparedDate)
today.setFullYear(comparedDateObj.getFullYear())
today.setMonth(comparedDateObj.getMonth())
today.setDate(comparedDateObj.getDate())
}
// Format the date part
const options: Intl.DateTimeFormatOptions = { day: 'numeric', month: 'long', year: 'numeric' };
const idFormat = birthDate.toLocaleDateString('id-ID', options);
// Format the date part
const options: Intl.DateTimeFormatOptions = { day: 'numeric', month: 'long', year: 'numeric' }
const idFormat = birthDate.toLocaleDateString('id-ID', options)
// Calculate age
let years = today.getFullYear() - birthDate.getFullYear();
let months = today.getMonth() - birthDate.getMonth();
let days = today.getDate() - birthDate.getDate();
// Calculate age
let years = today.getFullYear() - birthDate.getFullYear()
let months = today.getMonth() - birthDate.getMonth()
let days = today.getDate() - birthDate.getDate()
if (months < 0 || (months === 0 && days < 0)) {
years--;
months += 12;
}
if (months < 0 || (months === 0 && days < 0)) {
years--
months += 12
}
if (days < 0) {
const prevMonth = new Date(today.getFullYear(), today.getMonth() - 1, 0);
days += prevMonth.getDate();
months--;
}
if (days < 0) {
const prevMonth = new Date(today.getFullYear(), today.getMonth() - 1, 0)
days += prevMonth.getDate()
months--
}
// Format the age part
let extFormat = '';
if ([years, months, days].filter(Boolean).join(' ')) {
extFormat = `${years} Tahun ${months} Bulan ${days} Hari`;
} else {
extFormat = '0';
}
// Format the age part
let extFormat = ''
if ([years, months, days].filter(Boolean).join(' ')) {
extFormat = `${years} Tahun ${months} Bulan ${days} Hari`
} else {
extFormat = '0'
}
return {
idFormat,
extFormat
};
}
return {
idFormat,
extFormat,
}
}
// Date selection: default to today - today
export function getFormatDateId(date: Date) {
const dd = String(date.getDate()).padStart(2, '0')
const mm = monthsInId[date.getMonth()]
const yyyy = date.getFullYear()
return `${dd} ${mm} ${yyyy}`
}