특정 목표 시간까지 남은 시간을 일, 시, 분, 초 단위로 계산하여 표시하는 JavaScript 기능을 구현합니다. 또한, 현재 시간을 기준으로 당일 자정까지 남은 시간을 계산하는 기능도 함께 제공합니다.
1. 특정 목표 시간까지 남은 시간 계산
아래 코드는 현재 시간부터 지정된 미래 시간까지 남은 시간을 계산하여 콘솔에 출력합니다. 예시에서는 2021년 12월 1일 00시 00분까지의 남은 시간을 계산합니다.
function displayRemainingTime() {
// 목표 시간 설정 (년, 월-1, 일, 시, 분, 초)
const targetYear = 2021;
const targetMonth = 11; // 12월을 나타내기 위해 11 사용
const targetDay = 1;
const targetHour = 0;
const targetMinute = 0;
const targetSecond = 0;
// 목표 시간 밀리초로 변환
const targetTime = new Date(targetYear, targetMonth, targetDay, targetHour, targetMinute, targetSecond).getTime();
// 현재 시간 밀리초로 변환
const currentTime = Date.now();
// 시간 차이 (초 단위)
let timeDifferenceInSeconds = Math.floor((targetTime - currentTime) / 1000);
// 남은 일, 시, 분, 초 계산
const days = Math.floor(timeDifferenceInSeconds / (3600 * 24));
const hours = Math.floor((timeDifferenceInSeconds % (3600 * 24)) / 3600);
const minutes = Math.floor((timeDifferenceInSeconds % 3600) / 60);
const seconds = timeDifferenceInSeconds % 60;
// 결과를 콘솔에 출력 (두 자리로 포맷팅)
console.log(`${formatTimeUnit(days)}일 ${formatTimeUnit(hours)}시 ${formatTimeUnit(minutes)}분 ${formatTimeUnit(seconds)}초`);
// 1초 후 다시 실행
setTimeout(displayRemainingTime, 1000);
}
// 시간 단위를 두 자리로 포맷팅하는 헬퍼 함수
function formatTimeUnit(unit) {
return unit < 10 ? `0${unit}` : unit;
}
// 함수 실행
// displayRemainingTime(); // 필요시 주석 해제하여 실행
2. 현재 시간부터 당일 자정까지 남은 시간 계산
현재 시간을 기준으로 당일 밤 11시 59분 59초까지 남은 시간을 계산하여 콘솔에 출력합니다. 브라우저 개발자 도구(F12)에서 함수를 실행하면 결과를 확인할 수 있습니다.
function displayTimeToMidnight() {
// 현재 시간 밀리초로 변환
const now = new Date();
const currentTimeMillis = now.getTime();
// 다음 날 자정 시간 계산
const midnight = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 0, 0, 0);
const midnightMillis = midnight.getTime();
// 시간 차이 (초 단위)
let timeDifferenceInSeconds = Math.floor((midnightMillis - currentTimeMillis) / 1000);
// 남은 시, 분, 초 계산
// 참고: 당일 자정까지이므로 일 단위 계산은 필요 없으며, 남은 총 시간을 시로 변환 후 분, 초를 계산합니다.
const totalHoursRemaining = Math.floor(timeDifferenceInSeconds / 3600);
const hours = totalHoursRemaining % 24; // 남은 시
const minutes = Math.floor((timeDifferenceInSeconds % 3600) / 60);
const seconds = timeDifferenceInSeconds % 60;
// 결과를 콘솔에 출력 (두 자리로 포맷팅)
console.log(`${formatTimeUnit(hours)}시 ${formatTimeUnit(minutes)}분 ${formatTimeUnit(seconds)}초`);
// 1초 후 다시 실행
setTimeout(displayTimeToMidnight, 1000);
}
// 시간 단위를 두 자리로 포맷팅하는 헬퍼 함수 (이전 함수와 동일)
function formatTimeUnit(unit) {
return unit < 10 ? `0${unit}` : unit;
}
// 함수 실행
// displayTimeToMidnight(); // 필요시 주석 해제하여 실행