파란하늘의 지식창고
반응형

Dayjs 소개

기존에 Date 관련 라이브러리 중 가장 많이 사용하였던 momentjs는 현재 더 이상 개발되지 않고 있다.
https://momentjs.com/

이를 대체할 라이브러리로 date-fns, dayjs, luxon 등이 있으며 이전에 date-fns를 사용해 보았다.
dayjs가 가장 가볍다고 한다.
https://day.js.org/docs/en/installation/browser
https://suzzeong.tistory.com/115

현재 ECMAScript에서는 현재 기본으로 사용되는 범용성이 떨어지는 Date API를 대체할 Temporal API를 준비 중이지만 아직 정식 버전이 아닌 상태이다.
https://github.com/tc39/proposals
이후 표준 명세에 포함되면 기존 라이브러리 대체를 검토하면 된다.
(만약 우선 사용해보고 싶은 경우 Polyfill을 추가하고 사용해 볼 수 있다고 한다.
https://github.com/tc39/proposal-temporal#polyfills))

FE 개발을 하는 경우 대부분 node를 사용하여 프로젝트를 구성하고 react나 vue, svelte 같은 FE 프레임워크 기반하에 dayjs를 install 하여 사용하겠지만 FE 프레임워크 사용을 하지 않고 단순하게 browser에서 사용하는 방법을 정리해 보았다.

기본 사용 설정

https://day.js.org/docs/en/installation/browser

간단한 사용 방법은 다음과 같다.

<html>
<head>
    <script src="https://unpkg.com/dayjs"></script>
    <script>
        dayjs().format();    // 현재 날짜 출력 ex) '2024-03-12T04:40:02+09:00'
    </script>
</head>
</html>

Locale 설정

https://day.js.org/docs/en/i18n/loading-into-browser

locale 설정 시 사용할 locale을 추가로 호출해야 한다.

<html>
<head>
    <script src="https://unpkg.com/dayjs"></script>
    <script src="https://unpkg.com/dayjs/locale/ko.js"></script>
    <script>
        dayjs.locale('ko');
    </script>
</head>
</html>

상대 시간 설정

https://day.js.org/docs/en/plugin/relative-time

RelativeTime 플러그인을 추가해야 한다.

<html>
<head>
    <script src="https://unpkg.com/dayjs"></script>
    <script src="https://unpkg.com/dayjs/locale/ko.js"></script>
    <script>
        dayjs.locale('ko');
    </script>
    <script src="https://unpkg.com/dayjs/plugin/relativeTime"></script>
    <script>
        dayjs.extend(window.dayjs_plugin_relativeTime);
    </script>
    <script>
        dayjs().fromNow();    // 몇 초전
    </script>
</head>
</html>

plugin 추가하기

상대 시간 설정을 소개하면서 dayjs.extend를 사용하여 relativeTime plugin을 추가를 하였었다.

다양한 plugin들을  dayjs에서 사용할 수 있는데 browser 기준으로 추가하는 방법은 앞서 사용한 dayjs.extends를 사용하여 동일하게 추가할 수 있다.

https://day.js.org/docs/en/plugin/loading-into-browser

<!-- CDN example (jsDelivr) -->
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dayjs@1/plugin/utc.js"></script>
<script>dayjs.extend(window.dayjs_plugin_utc)</script>

 

반응형
profile

파란하늘의 지식창고

@Bluesky_

내용이 유익했다면 광고 배너를 클릭 해주세요