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; }