시계 만들기 (padStart, padEnd 함수 이용)

Juhyun·2023년 1월 11일
0
const clock = document.querySelector("h2#clock");

function getClock() {
  const date = new Date();
  clock.innerText = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
}

getClock(); //처음은 바로 실행
setInterval(getClock, 1000); // 그 후 1초마다 계속 반복 실행


모두 2자리수로 표시되도록 형식을 맞추기 위해, padStart 함수 이용

const clock = document.querySelector("h2#clock");

function getClock() {
  const date = new Date();
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");
  clock.innerText = `${hours}:${minutes}:${seconds}`;
}

getClock(); //처음은 바로 실행
setInterval(getClock, 1000); // 그 후 1초마다 계속 반복 실행

padStart 는 string에 쓸 수 있는 function
padStart (length, "앞에 추가할 문자")
padEnd (length, "뒤에 추가할 문자")

0개의 댓글