[JS] day.js

정세은·2023년 3월 15일
1

javascript

목록 보기
4/5

✔️ day.js

JavaScript로 작성된 라이브러리로, 날짜와 시간을 쉽게 다룰 수 있도록 도와주는 도구이다.
Moment.js와 유사한 기능을 제공하지만,
day.js는 Moment.js보다 약 33배 가볍고 빠르며 모듈식 설계를 채택하여 필요한 모듈만 가져와서 사용할 수 있다.

✔️ day.js 설치

npm install dayjs // npm을 사용하여 dayjs를 설치한다.
import dayjs from "dayjs"; // import 하여 사용하거나
const dayjs = require("dayjs"); // require 하여 사용할 수 있다.

✔️ 주요 기능

1️⃣ 파싱

day.js는 문자열로 된 날짜와 시간을 JavaScript Date 객체로 파싱할 수 있다.
예를 들어, 다음과 같이 문자열로 된 날짜를 day.js로 파싱할 수 있다.

const dayjs = require('dayjs');
                          
const date = dayjs('2023-03-15');

console.log(date.format('YYYY년 MM월 DD일')); // 2023년 03월 15일

2️⃣ 출력

day.js는 날짜와 시간을 원하는 형식으로 포맷팅하여 문자열로 변환할 수 있다.
예를 들어, 다음과 같이 날짜를 형식에 맞추어 문자열로 변환할 수 있다.

const dayjs = require('dayjs');
                          
const date = dayjs('2023-03-15');

console.log(date.format('YYYY년 MM월 DD일')); // 2023년 03월 15일

3️⃣ 비교

day.js는 두 날짜와 시간을 비교하는 기능을 제공한다.
예를 들어, 다음과 같이 두 날짜를 비교할 수 있다.

const dayjs = require('dayjs');

const date1 = dayjs('2023-03-15');
const date2 = dayjs('2023-03-16');

console.log(date1.isBefore(date2)); // true
console.log(date1.isAfter(date2)); // false
console.log(date1.isSame(date2)); // false

4️⃣ 연산

day.js는 날짜와 시간을 더하거나 빼는 기능을 제공한다.
예를 들어, 다음과 같이 날짜를 더하거나 빼서 새로운 날짜를 생성할 수 있다.

const dayjs = require('dayjs');

const date = dayjs('2023-03-15');

console.log(date.add(1, 'day').format('YYYY년 MM월 DD일')); // 2023년 03월 16일
console.log(date.subtract(1, 'month').format('YYYY년 MM월 DD일')); // 2023년 02월 15일

5️⃣ 로케일

day.js는 지역화된 날씨와 시간을 처리하는 기능을 제공한다.
예를 들어, 다음과 같이 한국 시간대로 지정하여 날짜를 생성할 수 있다.

const dayjs = require('dayjs');
const localizedFormat = require('dayjs/plugin/localizedFormat');
dayjs.extend(localizedFormat);

const date = dayjs('2023-03-15').locale('ko');
console.log(date.format('LL')); // 2023년 3월 15일

✔️ 적용

진행하고 있는 프로젝트에서 day.js를 사용하여 코드를 구현해봤다.

import dayjs from "dayjs";

...

useEffect(() => {
    const init = async () => {
      ...
      const accessTokenExpire = localStorage.getItem("access_token_expire");

      if (dayjs().add(10, "minute").isAfter(dayjs(accessTokenExpire))) {
        const refreshToken = localStorage.getItem("refresh_token");
        access_token = await getAccessTokenByRefreshToken(refreshToken)
          .then(data => {
          setToken(data);
          return data.access_token;
        })
      }
      ...
      // 생략
    };
    init();
}, []);

이 코드는 localStorage에서 저장된 token 만료 시간 값을 가져와 현재 시간에 10분을 더한 값이 만료 시간(accessTokenExpire)보다 큰지를 확인한다.
만약 그렇다면, 현재 token을 refresh token으로 교체한다.

✔️ 장점

1️⃣ 가볍고 유연한 라이브러리

day.js는 라이브러리의 크기가 작아서 브라우저에서 빠르게 로드되며, 필요한 기능만 선택하여 사용할 수 있다.
또한, 다양한 플러그인을 제공하여 개발자들이 필요한 기능을 추가로 확장하여 사용할 수 있다.

2️⃣ 높은 호환성

day.js는 자바스크립트 Date 객체와 완전히 호환되므로,
기존에 자바스크립트에서 사용되었던 Date 객체와 함께 사용할 수 있다.
또한, 다양한 프레임워크와 라이브러리와 호환성이 높아서 다른 라이브러리나 프레임워크와 함께 쉽게 사용할 수 있다.

3️⃣ 높은 성능

day.js는 빠르고 가벼워서, 대용량 데이터나 복잡한 계산을 처리할 때도 높은 성능을 보장한다.
또한, 브라우저 캐시를 이용하여 성능을 최적화할 수 있다.


이 밖에도 day.js에서 제공하는 함수는 정말 다양하다.
좀 더 자세한 내용은 공식 문서를 참고하면 좋을 것 같다.

https://day.js.org/en/

0개의 댓글