Javascript Date format

귀염둥이 어피치·2020년 11월 18일
0

moment.js 를 사용하지 않고도 날짜를 형식을 변경하는 function

data 인자는 아래와 같이 사용한다
date = new Date();

exports.dateConvert = function getFormatDate(date) {
  const year = date.getFullYear(); // yyyy
  let month = (1 + date.getMonth()); // M
  month = month >= 10 ? month : `0${month}`; // month 두자리로 저장
  let day = date.getDate(); // d
  day = day >= 10 ? day : `0${day}`; // day 두자리로 저장
  const hour = date.getHours(); // 시간 (24시간 기준, 2자리)
  const minutes = date.getMinutes(); // 분 (2자리)
  let second = date.getSeconds(); // 초 (2자리)
  second = second >= 10 ? second : `0${second}`;
  return `${year}-${month}-${day} ${hour}:${minutes}:${second}`;
};

리턴값은 필요에 따라 변경해서 가공하면 된다.

moment.js 를 사용해도 되지만
간단하게 date값을 받아 가공해서 사용하고 싶다면 적절한듯.

profile
어피치는 프론트엔드 개발자

0개의 댓글