본문 바로가기
IT관련/Javascript

[JavaScript] 웹 페이지에 시간 출력하는 방법

by 확고 2022. 4. 1.
728x90
반응형
 
현재 시간 : 오후 00시00분00초 

 

▼ 위와 같이 웹 페이지에 JavaScript로 시간 출력하는 방법
 
<style>
     #time{
     text-align:center;
     }
</style>
<script type="text/javascript">
     function showTime(){
     now = new Date();
     hours = now.getHours(); //현재 시간 오후 1시일 경우 13이 hours 변수에 들어감
     if(hours>=12){
     clock = "현재 시간 오후 " + (hours-12) + "시"
     }
     else{
     clock = "현재 시간 오전 " + hours + "시";
     }
     minutes = now.getMinutes();
     if(minutes<10){ //10분보다 작으면 0을 뒤에 붙이겠다
     clock += "0" + minutes + "분";
     }
     else{ //10분보다 작으면 0을 붙이지 않음
     clock += minutes + "분";
     }
     seconds = now.getSeconds();
     if(seconds<10){ //10초보다 작으면 0을 뒤에 붙이겠다
     clock += "0" + seconds + "초";
     }
     else{
     clock += seconds + "초";
     }
     var whakgo = document.getElementById("time"); //id가 time인 요소 정보를 whakgo 변수에 넣어줌
     whakgo.innerHTML = clock; //clock 변수를 넣어줌
     }

     //body 속성으로 onLoad 넣어도 되고 body 지우고 아래 주석 3줄처럼 해도 된다 ~ 

     //window.onload = function(){
     //setInterval(showTime,1000)
     //}
</script>
<body onLoad="setInterval(showTime,1000)"> <!-- 1초에 한 번씩 시간 나오게 하겠다 -->
     <div id="time"></div>
 </body>
 

728x90
반응형

댓글