본문 바로가기
html, javacript

[HTML][Java Script] 현재시간 출력하기

by 바디스 2020. 7. 4.

자바스크립트에서 Date()로 시스템의 시간을 받아올 수 있다.

또한, Date()가 가지고 있는 getHours, getMinutes, getSeconds 메소드를 이용 하여 시간, 분, 초 의 정보를 받아올 수 있다.

 

 

Date()로 시간을 받고 현재 시간의 시,분,초 로 나타내고 시간을 기준으로 오전과 오후로 나누어 보았다.

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    <style media="screen">
      #divClock{
        font-size: 30px;
        color: green;
      }
    </style>
    <script type="text/javascript">
      function showClock(){
        var currentDate = new Date();
        var divClock = document.getElementById('divClock');
        var msg = "현재 시간 : ";
        if(currentDate.getHours()>12){      //시간이 12보다 크다면 오후 아니면 오전
          msg += "오후 ";
          msg += currentDate.getHours()-12+"시 ";
       }
       else {
         msg += "오전 ";
         msg += currentDate.getHours()+"시 ";
       }
 
        msg += currentDate.getMinutes()+"분 ";
        msg += currentDate.getSeconds()+"초";
 
        divClock.innerText = msg;
 
        if (currentDate.getMinutes()>58) {    //정각 1분전부터 빨강색으로 출력
          divClock.style.color="red";
        }
        setTimeout(showClock,1000);  //1초마다 갱신
      }
    </script>
  </head>
  <body onload="showClock()">
    <div id="divClock" class="clock">
 
    </div>
  </body>
</html>
cs

댓글