[JS] D-day 계산

KJA·2022년 6월 15일
0

코드

const clock = document.querySelector('.clock');

function getDDay() {
    const today = new Date();
    const setDate = new Date('2022-12-25 00:00:00');

  	//밀리세컨드 단위로 나타내서 보여짐
    const dDay = setDate - today;

    const day = String(Math.floor(dDay / (1000 * 60 * 60 * 24))).padStart(2, '0');
    const hours = String(Math.floor((dDay / (1000 * 60 * 60)) % 24)).padStart(2, '0');
    const minutes = String(Math.floor((dDay / (1000 * 60)) % 60)).padStart(2, '0');
    const seconds = String(Math.floor((dDay / 1000) % 60)).padStart(2, '0');

    clock.innerText = `${day}${hours}시간 ${minutes}${seconds}초 남았습니다.`;
}

function init() {
    getDDay();
    setInterval(getDDay, 1000);
}

init();

함수

Math.floor()

주어진 숫자와 같거나 작은 정수 중에서 가장 큰 수를 반환합니다. 쉽게 말하면 소수를 버린다는 뜻입니다.

console.log(Math.floor(5.95)); // 5

console.log(Math.floor(5.05)); // 5

console.log(Math.floor(5)); // 5

console.log(Math.floor(-5.05)); // -6

밀리세컨드

나머지(%)연산을 할 때 시간, 분, 초의 단위에 맞춰 60 또는 24로 나눠주면 됩니다.

  • 계산할 날의 밀리초 / (1000 * 60 * 60 * 24) = 일
  • (계산할 날의 밀리초 / (1000 * 60 * 60)) % 24 = 시간
  • (계산할 날의 밀리초 / (1000 * 60)) % 60 = 분
  • (계산할 날의 밀리초 / 1000) % 60 = 초

padStart()

현재 문자열의 시작을 다른 문자열로 채워, 주어진 길이를 만족하는 새로운 문자열을 반환합니다. 채워넣기는 대상 문자열의 시작(좌측)부터 적용됩니다. String 일 때만 사용 가능합니다.

예시

'2'.padStart(3, '0'); // 002

'12'.padStart(2, '0'); // 이미 두 자리 수이므로 '12'가 반환됨

Math.floor((dDay / (1000 * 60 * 60))는 숫자이기 때문에 String()함수를 이용해 문자열로 변환 후 padStart()를 사용해서 두 자릿수로 만들어줍니다.

setInterval()

주기적으로 인자를 실행하는 함수입니다.

setInterval(getDDay, 1000); // 1초동안 getDay 함수를 주기적으로 실행합니다.

0개의 댓글