상세 컨텐츠

본문 제목

[바닐라js] D-Day 계산

JavaScript

by 마라랑랑 2022. 1. 4. 00:52

본문

const clockTitle = document.querySelector(".js-clock");

function setTimer() {
  const nowDate = new Date();
  const setDateYear = nowDate.getFullYear();
  const setDateMonth = nowDate.getMonth();
  const setDateDay = nowDate.getDate();

  let setYear = "";
  if (setDateMonth < 11) {
    setYear = setDateYear;
  } else if (setDateMonth === 11 && setDateDay < 25) {
    setYear = setDateYear;
  } else {
    setYear = setDateYear + 1;
  }
  const christDate = new Date(setYear, 11, 25);
  const remainder = christDate.getTime() - nowDate.getTime();

  const Day = Math.floor(remainder / (60 * 60 * 24 * 1000));
  const getHours = Math.floor(
    (remainder % (60 * 60 * 24 * 1000)) / (60 * 60 * 1000)
  );
  const getMinutes = Math.floor((remainder % (60 * 60 * 1000)) / (60 * 1000));
  const getSeconds = Math.floor((remainder % (60 * 1000)) / 1000);

  const hours = String(getHours).padStart(2, "0");
  const minutes = String(getMinutes).padStart(2, "0");
  const seconds = String(getSeconds).padStart(2, "0");
  const result = `${Day}d ${hours}h ${minutes}m ${seconds}s`;

  let inText = "";
  if (setDateMonth === 11 && setDateDay === 25) {
    inText = "D-Day";
  } else {
    inText = result;
  }
  clockTitle.innerText = inText;
}

setTimer();
setInterval(setTimer, 1000);
  • now Date() 를 const하여 현재 시간을 저장
  • nowDate.getFullYear() 를 통하여 현재시간의 년도를 추출
  • nowDate.getMonth() 를 통하여 현재 month 를 추출
  • nowDate.getDate() 를 통하여 현재시간의 날짜를 추출
  • D-day를 크리스마스로 설정할 경우
  • if 구문을 통하여 현재 월이 12월 미만이라면 setYear을 현재년도를 설정
  • if else 구문을 통하여 현재 월이 12월이며 25일 미만이라면 setYear을 현재년도를 설정
  • else 구문을 통하여 나머지 일수일 경우  setYear을 현재년도 +1 을 설정
  • 설정한 setYear년 12월 25일을 christDate로 const함
  • 크리스마스까지 남은 날짜를 christDate-nowDate 하여 남은 시간을 밀리초 단위로 표현하며 remainder로 const함
  • 남은 날짜 시간 분 초를 구해주며 const함
  • string 구문을 통하여 숫자를 문자로 추출 (padstart 함수를 사용하기 위해서)
  • padstart 구문을 통하여 2글자 미만의 숫자인 경우 앞자리에 0을 채워줌 ex) 7 ->07
  • if 구문을 통하여 12월 25일인 경우 D-Day 텍스트를 보여줌
  • 아닐경우 남은 시간을 보여줌
  • setInterval 함수를 통하여 setTimer함수가 1000밀리초마다 실행되게 해줌

 

 

 

'JavaScript' 카테고리의 다른 글

문법 - 연산자 (Operator)  (0) 2022.05.21
문법 - 식 (Expression)  (0) 2022.05.21
문법 - 변수 (Variable)  (0) 2022.05.21
문법 - 값 (Value)  (0) 2022.05.21
프로그래밍이란?  (0) 2022.05.21

관련글 더보기

댓글 영역