컴퓨터/JavaScript

JavaScript (1) - 자바스크립트를 이용하여 시계 구현하기

달서비 2020. 12. 14. 01:01

자바스크립트를 이용하여 시계를 만들어 보려고 합니다. 티스토리 블로그나 일부 다른 사이트에 사용하면 쉽게 사용할 수 있습니다.

 

모르시는 분들은 글을 아래로 내리면 코드를 스크랩해서 자신 블로그로 사용하시면 됩니다.

 

 

알아야 할 것

Date() - 시간과 관계있는 자바스크립트 객체
여기 글은 Date 객체의 일부 함수입니다.
getFullYear() 현재 년도를 부른다 (ex 2020)
getMonth() 현재 월을 부른다 (0~11로 부른다)
getDate() 현재 일을 부른다
getDay() 현재 요일을 부른다 (0~6으로 부른다)
getHours() 현재 시간을 부른다
getMinuites() 현재 분을 부른다
getSeconds() 현재 초를 부른다
Document.getElementByID() - 해당 html소스의 ID를 받아오는 함수 입니다.
document.getElementById("A").innerText id = "A" 라는 함수에 글을 추가한다.
document.getElementById("A").innerHTML id = "A" 라는 함수에 HTML 소스를 추가한다.

 

소스코드 공유

<!DOCTYPE html>

<head>
    <meta charset="utf-8">
    <title>자바스크립트 시계 구현</title>

    <style>
        /*CSS : 시계를 꾸미는 부분*/
        .Clock {
            width: 200px;
            height: 100px;
            text-align: center;
            color: #f4f4f4;
            background-color: black;
            padding-top: 10px;
        }
        #Clock {
            color: #F0C420;
            font-size: 24px;
        }
        #Clockday {
            color: #F0C420;
        }
    </style>
</head>

<body>
    <div class="Clock">
        What <b>time</b> is it now?<br>
        <div id="Clock">00:00</div>
        <div id="Clockday">00/00/00</div>
    </div>
    
    <script>
        function Clock() {
            var date = new Date();
            var YYYY = String(date.getFullYear());
            var MM = String(date.getMonth() + 1);
            var DD = Zero(date.getDate());
            var hh = Zero(date.getHours());
            var mm = Zero(date.getMinutes());
            var ss = Zero(date.getSeconds());
            var Week = Weekday();

            Write(YYYY, MM, DD, hh, mm, ss, Week);
           //시계에 1의자리수가 나올때 0을 넣어주는 함수 (ex : 1초 -> 01초)

            function Zero(num) {
                return (num < 10 ? '0' + num : '' + num);
            }

           //요일을 추가해주는 함수
            function Weekday() {
                var Week = ['일', '월', '화', '수', '목', '금', '토'];
                var Weekday = date.getDay();
                return Week[Weekday];
            }


           //시계부분을 써주는 함수
            function Write(YYYY, MM, DD, hh, mm, ss, Week) {
                var Clockday = document.getElementById("Clockday");
                var Clock = document.getElementById("Clock");
                Clockday.innerText = YYYY + '/' + MM + '/' + DD + '(' + Week + ')';
                Clock.innerText = hh + ':' + mm + ':' + ss;
            }
        }

        setInterval(Clock, 1000); //1초(1000)마다 Clock함수를 재실행 한다
    </script>
</body>

결과

What time is it now?
00:00
00/00/00