date-fns를 사용하면 간단하게 날짜를 컨트롤할 수 있다.

자바스크립트로 날짜를 다루기 위해서 Date() 객체를 사용한다.

그러나, 다소 불편하고 답답한 사용법 때문에 dayJS나 moment같은 라이브러리를 사용하기도 하는데, 이번에는 날짜를 컨트롤 할 때 불편함을 줄여주는 date-fns라는 라이브러리에 대해서 소개하고자 한다.

 

https://date-fns.org/

 

Modern JavaScript Date Utility Library

date-fns provides the most comprehensive yet simple and consistent toolset for manipulating JavaScript dates in a browser & Node.js.

date-fns.org

 

 

date-fns는 node 환경과 브라우저 환경에서 모두 안정적으로 작동하고 각 기능들이 모듈화 되어있기에 사용하기에 간편하다.

 

예를 들어, 1년 1개월 1일전의 날짜를 사용하는 코드를 통해서 date-fns의 편함을 느껴보자.

const currentDate = new Date();

const oneYearOneMonthOneDayAgo = new Date(
  currentDate.getFullYear() - 1,
  currentDate.getMonth() - 1,
  currentDate.getDate() - 1
);

console.log('1년 1개월 1일 전의 날짜:', oneYearOneMonthOneDayAgo);

 

기존에는 new Date()로 현재 날짜를 가져온 뒤 직접 현재 시간으로부터 -1 하여 년도, 월, 날짜를 구해야 했다.

 

date-fns를 통해서 좀 더 직관적으로 코드를 작성할 수 있다.

import { sub } from 'date-fns';

const currentDate = new Date();

const oneYearOneMonthOneDayAgo = sub(currentDate, {
  years: 1,
  months: 1,
  days: 1
});

console.log('1년 1개월 1일 전의 날짜:', oneYearOneMonthOneDayAgo);

 

sub 함수를 통해서 날짜를 계산할 수 있기 때문에 좀 더 짧고, 사용하기 편하며 알아보기에 직관적인 코드가 된다.

 

이외에도 런타임 환경 기준으로 날짜를 가져오는 코드의 특성상, timezone에 따른 문제가 발생하기도 한다.

 

date-fns를 사용하여 timezone 역시 컨트롤 할 수 있는데 간단한 예제를 통해서 살펴보자.

 

import { format, utcToZonedTime } from 'date-fns-tz';

const utcDate = new Date('2024-03-03T12:00:00Z'); // UTC 시간
const timezone = 'Asia/Seoul'; // 대한민국 표준시 (GMT+9)
const zonedDate = utcToZonedTime(utcDate, timezone);
console.log('현지 시간:', format(zonedDate, 'yyyy-MM-dd HH:mm:ss', { timeZone: timezone }));

 

위의 코드는 UTC 시간으로 생성된 Date를 한국 시간으로 변경하는 코드이다.

이렇게 타임존을 설정하면, 언제 어디서 코드를 호출해도 한국 시간을 계산할 수 있다.

 

시간을 다루는 작업은 중요하면서도 약간 복잡할 수 있고 놓치기 쉬운 부분이기 때문에 date-fns와 같은 라이브러리를 사용하면 더 높은 생산성을 제공받을 수 있는 것 같다.