[JavaScript] 현재 날짜를 가져와 YYYY-MM-DD 형식으로 만들기

Rachaen·2023년 5월 14일
0

방법 1

function getCurrentDate() {
    const date = new Date();
    const year = date.getFullYear();
    const month = ("0" + (date.getMonth() + 1)).slice(-2);
    const day = ("0" + date.getDate()).slice(-2);
    return `${year}-${month}-${day}`;
}

방법2

function getCurrentDate() {
    const date = new Date();
    const [year, month, day] = [
        date.getFullYear(),
        String(date.getMonth() + 1).padStart(2, '0'),
        String(date.getDate()).padStart(2, '0')
    ];
    return `${year}-${month}-${day}`;
}

padStart()

  • 문자열의 앞쪽에 지정한 길이만큼 다른 문자열로 채워 넣어주는 함수
  • str.padStart(targetLength, padString)
  • targetLength: 원하는 문자열 길이
  • padString(선택): 채우고 싶은 문자열. 기본값 ""
profile
개발을 잘하자!

0개의 댓글