Notice
Recent Posts
Recent Comments
Link
«   2025/10   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

죽이죽이

JS : Date 객체 사용해보기 본문

Javascript

JS : Date 객체 사용해보기

죽이죽이 2024. 1. 24. 15:05
  • Date 객체
※ 정의
- 날짜와 시간을 다루기 위한 내장 객체이다.


※ Date 객체를 사용한 Timer 구현
- HTML 코드
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="./css/app.css" />
  </head>
  <body>
    <div id="timer" class="timer">00 : 00</div>
    <script src="./js/app.js"></script>
  </body>
</html>​


- Javascript 코드

// 시작 시간 (형식 : Wed Jan 24 2024 14:54:06 GMT+0900)
const startDate = new Date();

// 타이머 구현
function timer() {
  let timerElement = document.querySelector("#timer");
  const nowDate = new Date();

  // new Date 로 감싸주지 않을 경우 ms 단위로 결과값 계산
  const difference = new Date(nowDate - startDate);

  // 1. getMinutes(), getSeconds() 함수를 사용해 분, 초를 가져옴
  // 2. toString() 함수를 사용해 가지고 온 값을 문자열로 변환
  // 3. 문자열에서 제공해주는 padStart() 함수를 사용해서 분, 초가 1글자일 때 앞에 0을 추가로 붙여줌
  const nowMinutes = difference.getMinutes().toString().padStart(2, "0");
  const nowSeconds = difference.getSeconds().toString().padStart(2, "0");

  // 백틱을 사용해서 텍스트 표시
  timerElement.innerText = `${nowMinutes} : ${nowSeconds}`;
}

// 1초마다 실행
setInterval(timer, 1000);​

 

- CSS 코드
.timer {
  font-size: 3rem;
  font-weight: bold;
}​

'Javascript' 카테고리의 다른 글

JS : SHA256 비밀번호 암호화  (0) 2024.01.31
JS : Wordle 클론코딩  (0) 2024.01.25
JS : WebAPI (setInterval, setTimeOut)  (0) 2024.01.24
JS : DOM 조작하기  (1) 2024.01.24
JS : 변수 선언, 자료형, 조건문, 반복문 정리  (0) 2024.01.24