티스토리 뷰

안녕하세요. 좋아요요정입니다! 

 

JavaScript Date형식 변경하는 함수 공유합니다.

(YYYY/MM/DD, YYYY년MM월 등등..)

 

 

기본구조

const getFormatDate = (date) => {
    const year = date.getFullYear();
    const month = (1 + date.getMonth());
    const day = date.getDate();
    return `${year}년 ${month}월 ${day}일 `; //Template literals 이용
}

1. 원하는 날짜를 인자로 받은 뒤

2. year, month, day 를 각각 저장하고

3. 원하는 형식으로 return해주는 함수입니다.

 

 

  Template literals?
  >>>MDN 사이트링크 포함합니다 
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Template_literals

 

 

사용 예시

const getFormatDate = (date) => {
    const year = date.getFullYear();
    const month = (1 + date.getMonth());
    const day = date.getDate();
    return `${year}년 ${month}월 ${day}일 `;
}

const today = new Date(); //오늘 날짜를 today에 저장
const dateFormat = getFormatDate(today); //날짜 형식을 dataFormat에 입력

 

응용 (YYYY/MM/DD)

const getFormatDate = (date) => {
    const year = date.getFullYear();
    const month = (1 + date.getMonth());
    month = month >= 10 ? month : `0${month}`; //10미만일 시 앞에 0을 붙혀서 저장
    const day = date.getDate();
    day = day >= 10 ? day : `0${day}`; //10미만일 시 앞에 0을 붙혀서 저장
    return `${year}/${month}/${day}`; // YYYY/MM/DD 형식으로 리턴
}

감사합니다!

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함