JavaScript

JS - 자바스크립트 시간출력

dev_SiWoo 2021. 4. 4. 14:35

1. HTML 부분

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Something</title>
    <link rel="stylesheet" href="index.css">
 
</head>
<body>
    <div class = "js-clock">
        <h1>00:00</h1>
    </div>
    <script src="clock.js"></script>
</html>
 
cs

 

2. JS부분

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const clockContainer = document.querySelector(".js-clock");
const clockTitle = clockContainer.querySelector("h1");
 
function getTime() {
  const date = new Date();
  const minutes = date.getMinutes();
  const hours = date.getHours();
  const seconds = date.getSeconds();
  clockTitle.innerHTML = `${hours < 10 ? `0${hours}` : hours}:${
    minutes < 10 ? `0${minutes}` : minutes
  }:${seconds < 10 ? `0${seconds}` : seconds}`;
}
 
function init() {
  getTime();
  setInterval(getTime, 1000);
}
 
init();
 
cs

 

3. 결과