생성 및 수정 측정할 수 있고, 현재 날짜를 출력하는 용도 등으로도 활용할 수 있다.
const date = new Date();
// new Date()로 현재 날짜 및 시간 을 가져올 수 있다
date
// Sat Apr 03 2021 14:20:42 GMT+0900 (대한민국 표준시)
date.getDay()
// 6
date.getMonth()
// 3
date.getHours()
// 14
date.getMinutes()
// 20
하지만 불러온 시간이 변경 되지는 않기 때문에 동적으로 시간변화를 보고 싶다면, setInterval()과 같은 비동기 호출 (타이머함수)을 이용하여 구현할 수 있다.
const getTime = function() {
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(); // 1초 단위로 시간을 불러와서 시계가 작동하는 것 같은 효과를 구현할 수 있다.