본문 바로가기

React/실험실

[React] dayjs

달력을 만드는 일이 생각보다 많이 귀찮다. 

 

그래서 보통 Antd의 Calendar를 많이 사용하는 편인데, 이번에 특정 값이 변경되면 달력의 선택된 날을 바꿔야하는 

일이 있었다. 

 

그러다가 알게된 것이 dayjs! 

 

기본적으로 Antd의 Calendar에서 제공하는 모든 함수는 dayjs의 값을 리턴한다. 

dayjs는 날짜와 관련된 작업을 도와주는 라이브러리이다. 

 

일반적으로 날짜와 관련된 작업을 할 때, 간단한 작업이면 Date, 복잡하다 싶으면 moment를 사용했는데, 

이번에 처음으로 사용하게 되었다. 

 

dayjs는 편의성은 moment와 비슷하지만 특별한 함수를 제공하고 있었다. 

바로 isAfter, isBefore, isBetween이다. 

 

이것은 날짜를 비교하는 함수인데, 아주 간단하게 비교가 가능했다. 

const dayjs = require('dayjs');

const date1 = dayjs('2023-06-07');
const date2 = dayjs('2023-06-09');

if (date1.isBefore(date2)) {
    console.log('2023-06-07 is before 2023-06-09');
} else {
    console.log('2023-06-07 is not before 2023-06-09');
}

날짜를 비교할 때 다음과 같이 간단하게 비교가 가능하다! 

 

isBetween이 아주 특별한데, 

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

const startDate = dayjs('2023-06-07');
const endDate = dayjs('2023-06-09');
const dateToCheck = dayjs('2023-06-08');

if (dateToCheck.isBetween(startDate, endDate)) {
    console.log('2023-06-08 is between 2023-06-07 and 2023-06-09');
} else {
    console.log('2023-06-08 is not between 2023-06-07 and 2023-06-09');
}

특정 날짜 사이의 데이터인지 바로 확인이 가능하다. 

반응형

'React > 실험실' 카테고리의 다른 글

[React] 메일 템플릿 만들기  (1) 2023.08.07
[React] day.js vs moment.js  (0) 2023.06.22
[React] MSW 잘 사용해보기  (0) 2023.06.08
[React] Cookie  (1) 2023.06.01
[React] Polymorphic 한 컴포넌트  (1) 2023.05.17