Javascript 날짜에 패턴 적용하기

2024. 12. 5. 16:52Javascript

function formatCustomDate(date, pattern) {
    // Replace year, month, day, hours, minutes, seconds dynamically
    const replacements = {
        'YYYY': date.getFullYear().toString(),
        'MM': (date.getMonth() + 1).toString().padStart(2, '0'),
        'DD': date.getDate().toString().padStart(2, '0'),
        'HH24': date.getHours().toString().padStart(2, '0'), // 24-hour format
        'HH': (date.getHours() % 12 || 12).toString().padStart(2, '0'), // 12-hour format
        'MI': date.getMinutes().toString().padStart(2, '0'),
        'SS': date.getSeconds().toString().padStart(2, '0')
    };

    // Replace the pattern placeholders with actual date values
    // Process replacements in a specific order to avoid conflicts (e.g., 'HH24' before 'HH')
    const keys = Object.keys(replacements).sort((a, b) => b.length - a.length); // Sort keys by length descending
    let formattedDate = pattern;
    for (const key of keys) {
        formattedDate = formattedDate.replace(new RegExp(key, 'g'), replacements[key]);
    }

    return formattedDate;
}

// Example usage
const now = new Date();
console.log(formatCustomDate(now, 'HH24:MI')); // Correct result: 15:12
console.log(formatCustomDate(now, 'YYYY-MM-DD HH24:MI:SS')); // Example: 2024-11-21 15:12:45