본문 바로가기
FRONTEND/Javascript

[Javascript] D-day 계산기

by LAY CODER 2021. 4. 23.

index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
  </head>

  <body>
    <div>
      <h1>Time Until Christmas Eve🎅</h1>
      <h2>26day 05hour 05minute 29second</h2>
    </div>
    <div></div>
    <script src="src/index.js"></script>
  </body>
</html>

 

styles.css

/* http://meyerweb.com/eric/tools/css/reset/ 
   v2.0 | 20110126
   License: none (public domain)
*/

/* Add Reset.css */

body {
  font-family: sans-serif;
}

div {
  width: 100vw;
  height: 50vh;
}

div:first-child {
  background: #bb2528;
  color: white;
  font-weight: 600;
  text-align: center;
}

h1 {
  padding: 90px 0px;
  font-size: 40px;
}

h2 {
  font-size: 30px;
}

div:nth-child(2) {
  background: #136b3a;
}

 

index.js

import "./styles.css";

const dDay = document.querySelector("h2");

// You're gonna need this
function getTime() {
  // Don't delete this.
  // 크리스마스 이브 날짜
  const xmasDay = new Date("2021-12-24:00:00:00+0900");
  // 현재 날짜
  const today = new Date();

  // 크리스마스 까지 남은 날짜 per millsecond
  const milliSecond = xmasDay - today;

  // 남을 날짜를 일,시간,분,초 로 나눔
  const second = Math.floor((milliSecond / 1000) % 60);
  const minute = Math.floor((milliSecond / 1000 / 60) % 60);
  const hour = Math.floor(milliSecond / 1000 / 60 / 60) % 24;
  const day = Math.floor(milliSecond / 1000 / 60 / 60 / 24);

  // d-day 문자열 생성
  const dDayInfo = `${day}day ${hour}hour ${minute}minute ${second}second`;

  dDay.innerText = dDayInfo;
}

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

 

 

 

Comment

 

원하는 new Date() 부터 현재 new Date() 까지 남은 날짜를 계산해주는 D-Day 계산기이다.

 

setInterval(getTime(), 1000) 을 통해 1초에 한번씩 함수를 실행시킨다.

댓글