기타

[라이브러리] dayjs, 날짜 라이브러리

ijooha 2025. 2. 19. 13:13

dayjs 라이브러리 사용하기

 


       dayjs란? 

dayjs는 날짜를 관리해주는 라이브러리이다.

달력을 만들어볼 일이 있어서 찾아봤는데, 리액트에서 제공해주는 달력은 커스터마이징이 어렵고 자유도가 떨어져서,

그냥 날짜를 가져다 써서 달력을 만들기로 했다! 날짜 라이브러리도 다양했지만 그중 가장 가벼운 dayjs를 쓰기로 했다.

 

우선 라이브러리를 설치해야 한다.

npm install dayjs

 

 


       기본 메소드 

dayjs에는 다양한 메소드가 존재하는데, 가장 기본적인 메소드는 이러하다.

현재 날짜 dayjs()
현재 년도 dayjs().year() //month, date, day 등으로도 사용 가능
날짜 더하기 dayjs().add(1, 'year')
날짜 빼기 dayjs().subtract(1, 'year')
특정 날짜 설정 dayjs().set('year', 2026) //(년도만 2026으로 변경)
날짜 차이 계산 dayjs().diff(비교할 날짜, 'date') //비교 날짜와 며칠 차이인지 계산, 시간, 분, 초 단위 가능

 

 


       응용하기 

달력을 만들기 위해 필요한 정보는 두 가지이다.

  • 한 달이 며칠인지
  • 그 달의 첫 번째 날짜가 무슨 요일인지

이를 활용해 `.add('month', 1)` 또는 `.subtract('month', 1)`을 이용하면 이전 달과 다음 달을 구현할 수 있다.

dayjs().daysInMonth() // 한 달이 며칠인지 반환
dayjs().startOf('month').day() // 해당 달의 첫 번째 요일 (숫자로 반환, 월요일=1)

이제 이를 활용해 달력을 구현해보자!

import styled from "styled-components";
import dayjs from "dayjs";
import "dayjs/locale/ko";
dayjs.locale("ko");

const StCalendarGrid = styled.div`
  display: grid;
  grid-template-columns: repeat(7, auto);
  justify-content: start;
  border: 1px solid blue;
`;
const StCalendarBox = styled.div`
  width: 160px;
  height: 160px;
  border: 1px solid red;
`;

const daysName = ["월", "화", "수", "목", "금", "토", "일"];
const emptyDays = dayjs().startOf("month").day() - 1;
const daysInMonth = dayjs().daysInMonth();

const Calendar = () => {
  return (
    
      {daysName.map((day) => (
{day}
      ))}
      {[
        ...Array(emptyDays).fill(""), // 빈 칸
        ...Array.from({ length: daysInMonth }, (_, i) => i + 1), // 날짜
      ].map((el, index) => (
        {el || "empty"}
      ))}
    
  );
};

export default Calendar;

 

 


더보기

라이브러리를 사용할수록 새로운 기능을 쉽게 구현할 수 있어서 흥미롭다.

앞으로 더 많은 라이브러리를 활용해봐야겠다!

'기타' 카테고리의 다른 글

[gitHub] 커밋 컨벤션  (0) 2025.01.29
[gitHub] 깃허브 시작하기  (1) 2024.12.23