react-dayjs

day.js 는 많은 JavaScript 날짜 관련 라이브러리중 가장 가벼운 라이브러리이다.

day.js의 사용방법에 대해 알아보도록 하자.


day.js 선택한 이유

Moment.js는 사이즈가 매우 큰 라이브러리이다. 사용하지도 않는 기능들로 인해 페이지 렌더링 시간은 늘어난다는 단점이 있었다.

Moment.js의 공식 문서에 Moment.js를 대체하기에 좋은 라이브러리들이 소개되어 있다.

Day.js는 기본적인 기능만 포함하여 매우 작은 사이즈, 플러그인을 사용한 확장, Moment.js와 똑같은 인터페이스를 가지고 있어 선택하게 되었다.


day.js 설치


npm install dayjs

timeForToday.js


댓글 작성 시간을 구현하기 위해 day.js를 사용했다.

import dayjs from 'dayjs';
import 'dayjs/locale/ko';
import relativeTime from 'dayjs/plugin/relativeTime';
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';

export const timeForToday = (time) => {
  dayjs.extend(relativeTime);
  dayjs.locale('ko');
  dayjs.extend(utc);
  dayjs.extend(timezone);

  // 현재 날짜 및 시간 객체 생성
  const parsedDate = dayjs(time, 'YYYY-MM-DD HH:mm:ss').add(9, 'hours');
  return parsedDate.fromNow();
};

add() 함수를 사용해 원하는 날짜 및 시간을 더할 수 있다.


comment.js


<Item>{timeForToday2(comment.createdAt)}</Item>

결과 화면



comment10-2.gif