Post

Dayjs 사용법 정리

Day.js 라이브러리 사용법 정리

날짜와 시간을 다룰 때 Day.js를 많이 사용하는데, 필요할 때마다 찾아 보기 위한 용도로 사용법을 정리한다.

설치

1
npm install dayjs

객체 생성

현재 날짜

1
2
3
4
5
6
7
import dayjs from "dayjs";

// 현재 날짜
const now1 = dayjs();

// Date 객체로도 가능
const now2 = dayjs(new Date());

시간 지정

1
2
3
4
5
6
7
import dayjs from "dayjs";

// 날짜 지정
const date1 = dayjs("2018-04-13");

// 날짜 + 시간 지정
const date2 = dayjs("2018-04-13 19:18");

포맷

format 함수를 사용하면 날짜가 지정한 양식으로 반환된다.

1
dayjs("2019-01-25").format("DD/MM/YYYY"); // '25/01/2019'

사용 가능한 양식은 여기를 참고하자.

가져오기

get 함수 사용

1
2
3
4
5
6
7
import dayjs from "dayjs";

const date = dayjs("2018-04-13");

date.year(); // 2018
date.month(); // 3 <- 월은 0부터 시작한다. 1월 = 0
date.date(); // 13

month는 0부터 시작함에 주의하자.

원하는 포맷에 맞게 가져오기

월과, 일은 두 자리로 표시하고 요일은 월요일과 같이 한글로 표시하기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import dayjs from "dayjs";
import "dayjs/locale/ko";

const getFormattedDate = (date: Date) => {
  const dayjsDate = dayjs(date);
  return {
    year: dayjsDate.year(),
    month: dayjsDate.format("MM"),
    date: dayjsDate.format("DD"),
    day: dayjsDate.locale("ko").format("dddd"),
  };
};

// 반환 값 확인
const { year, month, date, day } = getFormattedDate(new Date("2024-8-3"));
console.log(year, month, date, day); // 2024, 08, 03, 토요일
  • M: 월을 한 자리로 표시 (3) / MM: 월을 두 자리로 표시 (03)
  • 일도 마찬가지로 D는 한 자리 / DD는 두 자리로 표시
  • 한글로 요일을 가져오려면 localeko로 지정. formatdddd로 설정하여 월요일과 같이 가져온다.
    • ❗️상단에 dayjs/locale/ko를 import 해야 한다.
    • 한 글자로 하려면 ddd로 설정 (월, 화)

날짜 계산하기

1
2
const a = dayjs('2024-08-06')
const b = a.add(7, 'day') // 2024-08-13

날짜 계산 시 원래 값은 변경되지 않고 계산된 day.js 객체가 반환된다. (a의 값은 여전히 ‘2024-08-06’)

사용 가능한 단위 목록

UnitShorthand
dayd
weekw
monthM
quarterQ
yeary
hourh
minutem
seconds
millisecondms

Unit은 대소문자를 구분하지 않고, Shorthand는 대소문자를 구분한다.

🧑‍💻 이전/다음 달로 변경 예제

Prev 클릭 시 현재 날짜에서 1개월을 빼고, Next 클릭 시 1개월을 더하여 월을 조정할 수 있는 예제

HTML

1
2
3
4
5
<div class="flex items-center gap-3 m-2">
  <button class="btn btn-primary" id="prev">Prev</button>
  <h1 class="text-3xl font-bold" id="date"></h1>
  <button class="btn btn-primary" id="next">Next</button>
</div>

Script

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
document
  .querySelector("#prev")
  .addEventListener("click", () => changeMonth(-1));

document
  .querySelector("#next")
  .addEventListener("click", () => changeMonth(1));

const $date = document.querySelector("#date");

let date = dayjs(); // 현재 날짜로 초기화

displayDate(dayjs());

function changeMonth(value) {
  // 현재 날짜에 월을 더하거나 빼기
  date = date.add(value, "M");
  displayDate();
}

function displayDate() {
  // "2024년 08월" 형식으로 출력
  $date.innerHTML = date.format("YYYY년 MM월");
}

result

This post is licensed under CC BY 4.0 by the author.