자바스크립트 예제

디지털 시계 : new Date() -> getMonth()+1, getDate(), getDay()

자무카 2022. 12. 31.

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="./style.css">
    <!-- <script defer src="./timer.js" type="text/javascript"></script> -->
</head>

<body>
<div class="clock">
    <div class="now" id="now"></div>
    <div class="today" id="today"></div>
    <div class="time" id="time"></div>
</div>  

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

nowDiv.textContent = "new Date()";
todayDiv.textContent = "날짜";
timeDiv.textContent = "시간";

function getTime() {
    // console.log("getTime 테스트");
    // const WEEKDAY = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];
    const WEEKDAY = ["일", "월", "화", "수", "목", "금", "토"];
    let now = new Date();

    let year = now.getFullYear();
    let month = now.getMonth() + 1; // 3항 연산자 재할당 -> const X
    let day = now.getDate();
    // 요일 구하기
    // 1) getDay()  2) new Date()->toString()->slice
    // console.log(now.getDay());
    let weekday1 = WEEKDAY[now.getDay()];
    let weekday2 = now.toString().slice(0, 3);
    let hour = now.getHours();
    let min = now.getMinutes();
    let sec = now.getSeconds();

    month = (month < 10) ? `0${month}`: month
    day = (day < 10) ? `0${day}`: day
    hour = (hour < 10) ? `0${hour}`: hour
    // min = (min < 10) ? `0${min}`: min
    sec = (sec < 10) ? `0${sec}`: sec
    
    nowDiv.textContent = now; // innerText는 눈에 보이는 것만
    todayDiv.textContent = `${year}년 ${month}월 ${day}일 ${weekday1}`;
    timeDiv.textContent = `${hour}시 ${min}분 ${sec}초`;
    
}

setInterval(getTime, 1000);
* {
    box-sizing: border-box;
    font-size: 32px;
}
body{
    margin: 0;
    color: rgb(255,255,255);
    background-color: rgb(0,0,0);
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
}
.clock{
    min-width: 360px;
    margin: 0 auto;;
    padding: 50px 0;
    text-align: center;
    border: 1px solid rgb(255,255,255);
    border-radius: 10px;
}
.now{
    font-size: 14px;
    margin-bottom: 10px;
    
}
.today{
    margin-bottom: 10px;
}
.time{
    margin-top: 10px;
}

댓글