50 lines
1.5 KiB
TypeScript
50 lines
1.5 KiB
TypeScript
export function formatDate(
|
|
date: Date | string | number | null | undefined,
|
|
option:
|
|
| 'full'
|
|
| 'long'
|
|
| 'medium'
|
|
| 'short'
|
|
| 'numeric'
|
|
| 'yearMonth'
|
|
| 'dayMonth'
|
|
| 'time'
|
|
| Intl.DateTimeFormatOptions,
|
|
): string {
|
|
if (!date) {
|
|
return 'Tidak ada data tanggal'
|
|
}
|
|
|
|
const listOptions: { [key: string]: Intl.DateTimeFormatOptions } = {
|
|
full: { day: 'numeric', month: 'long', year: 'numeric' },
|
|
long: { day: 'numeric', month: 'long', year: 'numeric' }, // Mirip 'full' tapi bisa disesuaikan
|
|
medium: { day: 'numeric', month: 'short', year: 'numeric' },
|
|
short: { day: '2-digit', month: '2-digit', year: '2-digit' },
|
|
numeric: { day: 'numeric', month: 'numeric', year: 'numeric' },
|
|
yearMonth: { month: 'long', year: 'numeric' },
|
|
dayMonth: { day: 'numeric', month: 'long' },
|
|
time: { hour: 'numeric', minute: 'numeric', second: 'numeric' },
|
|
}
|
|
|
|
let options: Intl.DateTimeFormatOptions | undefined
|
|
|
|
if (typeof option === 'string' && listOptions[option]) {
|
|
options = listOptions[option]
|
|
} else if (typeof option === 'object' && option !== null) {
|
|
options = option // Menggunakan opsi yang diberikan langsung
|
|
} else {
|
|
console.warn(
|
|
`Opsi format tanggal "${option}" tidak valid. Menggunakan format 'full' sebagai default.`,
|
|
)
|
|
options = listOptions.full
|
|
}
|
|
|
|
try {
|
|
const dateObject = new Date(date)
|
|
return dateObject.toLocaleDateString('id-ID', options)
|
|
} catch (error) {
|
|
console.error('Gagal memformat tanggal:', error)
|
|
return 'Format tanggal tidak valid'
|
|
}
|
|
}
|