HTML, CSS, Javascript

[Javascript] 날짜 계산하는 프로그램 만들기

웅지니어링 2021. 8. 7. 17:36

먼저 CSS를 통해 만들고자 하는 프로그램의 뼈대를 구축한다.

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>독서 챌린지</title>
  <style>
    #container{
      margin:50px auto;
      width:300px;
      height:300px;
      border-radius:50%;
      border:2px double #222;
      background-color:#d8f0fc;
      text-align: center;
    }
    h1 {
      margin-top:80px;
    }
    .accent {
      font-size:1.8em;
      font-weight:bold;
      color:red;
    }
  </style>
</head>
<body>
  <div id="container">
    <h1>책 읽기</h1>
    <p><span class="accent" id="result"></span>일 연속으로 <br> 책 읽기를 달성했군요.</p>
    <p>축하합니다!</p>
  </div>  

</body>
</html>

현재 이 코드를 실행시키게 되면 아래와 같은 결과가 나타난다.

 

이제 여기서 해야할건 '일' 글자 앞에 계산한 일수를 추가하는 것뿐이다.

<script>
var now = new Date("2020-10-15");       // 오늘 날짜를 객체로 지정
    var firstDay = new Date("2020-10-01");   // 시작 날짜를 객체로 지정

    var toNow = now.getTime();         // 오늘까지 지난 시간(밀리 초)
    var toFirst = firstDay.getTime();  // 첫날까지 지난 시간(밀리 초) 
    var passedTime = toNow - toFirst;  // 첫날부터 오늘까지 지난 시간(밀리 초)

    passedTime = Math.round(passedTime / (1000 * 60 * 60 * 24));  // 밀리 초를 일 수로 계산하고 반올림

    document.querySelector('#result').innerText = passedTime;
</script>

accent 클래스의 ID인 'result'를 document.querySelector를 통해 지정을 해준 후 계산된 일 수인 passedTime을

대입해주면 프로그램은 완성된다.

완성된 프로그램