본문 바로가기
부트캠프교육중/JavaScript

[JS] new Date

by 뭉지야 2023. 8. 10.
728x90

new Date()

new Date().getDate()

new Date().getDay()   // 0이면 일요일이라는 의미이다.

new Date().getFullYear()  //년도

new Date().getHours()  //시

new Date().getMinutes()  //분

new Date().getSeconds()

 


시계만들기

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

setInterval(getClock, 1000);

근데 이 상태로 하니까 시계가 1초 지나서 뜬다. 

그래서 시계가 바로 보이도록 하기 위해서 getClock을 불러온다.

 

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

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

getClock();
setInterval(getClock, 1000);

 

근데 저렇게 하니까 1초일때 일반 시계처럼 01보이는게 아니고 1 이렇게 뜬다 .

이걸 01로 뜨게 수정해줄것이다.

padStart를 이용할건데!! 

padStart의 앞은 number가 아닌 String이여야 한다!!!

"1".padStart(2, "0")       // "01"

글자의 길이를 2로 맞춰주려고 한다. 길이가 2가 되지 않는다면 앞쪽에 0을 추가해줘라

"12".padStart(2, "0")      // "12"

"hello".padStart(20, "x")    // "xxxxxxxxxxxxxxxhello"

 

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);

 

728x90

'부트캠프교육중 > JavaScript' 카테고리의 다른 글

[JS] express  (0) 2023.08.11
[JS] Math  (0) 2023.08.10
[JS] str.substr  (0) 2023.08.10
[JS] return  (0) 2023.08.06
String.prototype.trim()  (0) 2023.08.04