본문 바로가기
JavaScript

현재 시간 출력하는 방법

by 잔크립트 2021. 6. 20.
const clockContainer = document.querySelector('.js-clock'),
clockTitle = clockContainer.querySelector('h1');

    console.log('clockContainer:', clockContainer);
    console.log('clockTitle:', clockTitle);

    function getTime() {
        const date = new Date();
        const hours = date.getHours();
        const minutes = date.getMinutes();
        const seconds = date.getSeconds();
        clockTitle.innerText = `${hours < 10 ? `0${hours}` :hours}:${minutes < 10 ? `0${minutes}` : minutes}:${seconds < 10 ? `0${seconds}` : seconds}`;
    }

    function init() {
        getTime();
        setInterval(getTime, 1000);
    }

    init();

JS는 이렇게

<body>
    <div class="container">
        <div class="center_box">
            <div class="js-clock">
                <h1>00:00:00</h1>
            </div>
        </div>
    </div>
    <script src="clock.js"></script>
</body>

html은 이렇게 작성하면

이렇게 출력할 수 있습니다 !

LIST

'JavaScript' 카테고리의 다른 글

자바스크립트(JavaScript 기초)  (0) 2021.06.19
Java Script 입문  (0) 2021.06.17