Files
simrsx-fe/app/lib/date.ts
2025-11-05 13:19:07 +07:00

52 lines
1.5 KiB
TypeScript

export function getAge(dateString: string, comparedDate?: string): { idFormat: string; extFormat: string } {
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());
}
// 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();
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--;
}
// 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
};
}
export function formatDateYyyyMmDd(isoDateString: string): string {
const date = new Date(isoDateString);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}