Develop record

[Javascript] 디지털 시계 만들기 본문

Programming Language/Javascript

[Javascript] 디지털 시계 만들기

seong's log 2024. 1. 14. 05:46
*{
    font-size: 30px;
}
body{
    display: flex;
    justify-content: center;
    align-items: center;
    height:80vh;
    background-color: black;
    color: white;
}
.clock{
    border: 1px solid white;
    border-radius: 10px;
    text-align: center;
    width: 360px;
    padding: 50px 0;
    margin: auto;
}
.today{
    margin-bottom: 10px;
}
.time{
    margin-top: 10px;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>디지털 시계</title>
    <link rel="stylesheet" href="digitalClock.css">
</head>
<body>
   
    <div class="clock">
        <!-- class : css 적용 시/ id : script에서 요소 선택 시 많이 사용 -->
        <div class="today" id="today"></div>    
        <div class="time" id="time"></div>
    </div>

    <script src="digitalClock.js"></script>
</body>
</html>
const todayDiv = document.getElementById("today")
const timeDiv = document.getElementById("time")

function getTime(){
    let now = new Date();        //1초마다 출력하기
    //timeDiv.textContent = now;
    let year = now.getFullYear();   //현재의 년도를 가져옴
    let month = now.getMonth() + 1; //1월 - 12월 => 0 - 11 이기 때문에 +1을 해줘야함 
    let date = now.getDate();
    let hour = now.getHours();
    let minute = now.getMinutes();
    let second = now.getSeconds();

    month = month < 10 ? `0${month}`: month
    date = date < 10 ? `0${date}`: date
    hour = hour < 10 ? `0${hour}`: hour
    minute = minute < 10 ? `0${minute}`: minute
    second = second < 10 ? `0${second}`: second

    todayDiv.textContent = `${year}년 ${month}월 ${date}일`
    timeDiv.textContent = `${hour}시 ${minute}분 ${second}초`
}
getTime() //setInterval은 1초가 지나고 나오기 때문에 새로고침하자마자 지금의 시간을 보기 위해
setInterval(getTime,1000)   //함수명, ms시간