Javascript 현재 시간을 15단위로 표시하기

2024. 12. 5. 17:59Javascript

function getCurrentTimeRoundedTo15Minutes() {
    const now = new Date();

    // Get the current hour and minute
    const hours = now.getHours();
    const minutes = now.getMinutes();

    // Round minutes to the nearest 15-minute increment
    const roundedMinutes = Math.round(minutes / 15) * 15;

    // Handle overflow of minutes (e.g., 60 minutes = next hour)
    const adjustedHours = (roundedMinutes === 60) ? (hours + 1) % 24 : hours;
    const finalMinutes = (roundedMinutes === 60) ? 0 : roundedMinutes;

    // Format hours and minutes as HH24:MI
    const formattedTime = `${adjustedHours.toString().padStart(2, '0')}:${finalMinutes.toString().padStart(2, '0')}`;

    return formattedTime;
}

// Example usage
console.log(getCurrentTimeRoundedTo15Minutes()); // Output: e.g., "15:15" or "15:30"