자바스크립트 현재시간 실시간 - jabaseukeulibteu hyeonjaesigan silsigan

웹페이지에 자바스크립트를 이용하여 현재시간을 표시 하려고한다. 

new Date()에 대해 정리하려고합니다.

new Date()로 현재 날짜와 시간을 담은 Date 객체를 구할 수 있습니다.

const now = new Date(); // 현재 날짜 및 시간 console.log(now); //콘솔출력값: Wed Oct 27 2021 12:07:54 GMT+0900 (한국 표준시)

const now = new Date() 

console.dir(now)를 실행시키면 가져올수있는 객체들이 쫙 나온다.

아래 이미지에 가져올 수 있는 년,월,일,시,분,초 등이 나타나있다.

now

연도 구하기

데이터 객체 getFullYear()를 이용한다.

const now = new Date(); // 현재 날짜 및 시간 const year = now.getFullYear(); console.log(year) //콘솔출력값: 2021

월 구하기

데이터 객체 getMonth()를 이용한다.

const now = new Date(); // 현재 날짜 및 시간 const month = now.getMonth(); console.log(month) //콘솔출력값: 10

 

일 구하기

데이터 객체 getDate()를 이용한다.

const now = new Date(); // 현재 날짜 및 시간 const date = now.getDate(); console.log(date) //콘솔출력값: 27

시간 구하기

데이터 객체 getHours()를 이용한다.

const now = new Date(); // 현재 날짜 및 시간 const hours = now.getHours(); console.log(hours) //콘솔출력값: 12

분 구하기

데이터 객체 getMinutes()를 이용한다.

const now = new Date(); // 현재 날짜 및 시간 const minutes = now.getMinutes(); console.log(minutes) //콘솔출력값: 19

초 구하기

데이터 객체 getSeconds()를 이용한다.

const now = new Date(); // 현재 날짜 및 시간 const seconds = now.getSeconds(); console.log(seconds) //콘솔출력값: 35

웹페이지에 실시간 표시하기

우선 html바디태그에 시간이 들어갈 h2태그를 설정해준다.

기본시간을 00:00:00으로 설정해준다.

<body> <h2 id="clock">00:00:00</h2> ....<중략> </body>

자바스크립트에서 id clock를 변수 선언 해줍니다.

const clock = document.getElementById("clock");

function getClock() 에 시간, 분, 초에 대한 변수를 선언한뒤 html에 표시될 수있도록  clock안에

clock.innerText로 `${hour}:${minutes}:${seconds}` 를 삽입해준뒤 함수를 실행했습니다.

const clock = document.getElementById("clock"); function getClock(){ const now = new Date(); // 현재 날짜 및 시간 const hour = now.getHours(); const minutes = now.getMinutes(); const seconds = now.getSeconds(); clock.innerText = `${hour}:${minutes}:${seconds}`; } getClock();

현재시간이 잘 표현되었으나 두가지 문제가 발생했습니다.

1.현재시간이 표시는 되나 새로고침을 해야지만 실시간이 반영된다. (새로고침 안해도 자동으로 되게하여야함 )

2.시, 분, 초를 두자리 수로 나타나게 하고싶다. (ex:14:03:09)

1.현재시간이 표시는 되나 새로고침을 해야지만 실시간이 반영된다. (새로고침 안해도 자동으로 되게하여야함)

각 호출 사이에 고정된 시간 지연으로 함수를 반복적으로 호출하거나 코드 조각을 실행하는  setInterval()를 사용합니다.

문법: setInterval(function[, delay]);

const clock = document.getElementById("clock"); function getClock(){ const now = new Date(); // 현재 날짜 및 시간 const hour = now.getHours(); const minutes = now.getMinutes(); const seconds = now.getSeconds(); clock.innerText = `${hour}:${minutes}:${seconds}`; } getClock(); setInterval(getClock, 1000);

getClock();을 실행하여 해당 웹페이지를 열자마자 바로 실시간이 나올수 있도록 해준다.(안해주면 초기값 00:00:00 나오고 바뀜)

위처럼 적용하면 새로고침이 없이  작동되는것을 확인할수있다.

2.시, 분, 초를 두자리 수로 나타나게 하고싶다. (ex:14:03:09)

String.prototype.padStart()

padStart() 메서드를 사용. 현재 문자열의 시작을 다른 문자열로 채워, 주어진 길이를 만족하는 새로운 문자열을 반환합니다. 채워넣기는 대상 문자열의 시작(좌측)부터 적용됩니다.   **String을 받아야합니다.!!**

ex padStart() 

const str1 = '5'; console.log(str1.padStart(2, '0')); // expected output: "05"

적용

function getClock(){ const now = new Date(); // 현재 날짜 및 시간 const hour = now.getHours().padStart(2,"0"); const minutes = now.getMinutes().padStart(2,"0"); const seconds = now.getSeconds().padStart(2,"0"); clock.innerText = `${hour}:${minutes}:${seconds}`; } getClock(); setInterval(getClock, 1000);

위 코드처럼 구현하면 될 것 같지만 적용이 안된다. 이유는  **String을 받아야하기 때문이다. 변수 hour, minutes, seconds는 셋 중 하나인 hour의 타입을 찍어보면  |  console.log(typeof hour)    ===> number로 출력된다. 해당 number를 String으로 변환해주면 끝이다.

String(thing) 사용!

function getClock(){ const date = new Date() const hour = String(date.getHours()).padStart(2,"0"); const minutes = String(date.getMinutes()).padStart(2,"0"); const second = String(date.getSeconds()).padStart(2,"0");//number이기 때문에 padStart 붙일 수 없음. String 변환해주어야한다. clock.innerText = `${hour}:${minutes}:${second}`; } getClock(); setInterval(getClock, 1000);

위 코드를 적용하면 웹페이지 내에서 정상작동하는것을 볼 수 있다.

출처: 니꼬선생님 바닐라자바스크립트로 크롬웹만들기 강의를 듣고 정리한 내용입니다.

Toplist

최신 우편물

태그