본문 바로가기
728x90
반응형

올해 새로운 프로젝트를 맡게 되면서 달력에 서버에 있는 데이터를 보여줘야하는 기능을 구현하게 되었다. 

다양한 라이브러리가 있었지만 디자이너의 요구에 맞는 달력을 제작하기가 어려워 date-fns를 사용하여 커스텀 달력을 만들어보았다. 

 

date-fns란?

date-fns는 JavaScript와 TypeScript를 위한 유용한 날짜 관련 유틸리티 라이브러리이다.

이 라이브러리는 날짜를 다루는 다양한 함수를 제공하여 날짜 및 시간 관련 작업을 쉽게 처리할 수 있도록 도와주며 날짜 비교, 날짜 추가, 일,달,년, 요일 계산등의 다양한 기능이 많다.

 

date-fns 라이브러리 설치하기

아래 코드를 입력하여 설치할 수 있다.

npm install date-fns --save
# or with yarn
yarn add date-fns

 

다양한 함수 사용하기

date-fns에서는 사용하고 싶은 함수들을 import하여 사용할 수 있는데 const 값에 원하는 함수의 결과값을 저장하여 활용할 수 있다. 

아래는 예시 코드로 현재 날짜를 설정하는 방법과 날짜의 덧셈 뺄셈, 날짜 차이 계산, 포매팅 등의 예시 코드를 적어두었다. 

*포매팅이란 지정한 날짜에 대해 원하는 형식으로 변환하는 것을 말한다. 

import {
  addDays,
  addMonths,
  addYears,
  differenceInDays,
  differenceInMonths,
  differenceInYears,
  format,
  isAfter,
  isBefore,
  isSameDay,
  isValid,
  parseISO,
  startOfDay,
  startOfMonth,
  startOfYear,
} from 'date-fns';

// 현재 날짜
const today = new Date();

// 날짜 덧셈과 뺄셈
const tomorrow = addDays(today, 1); // 현재 날짜에 1일을 더한 날짜
const nextWeek = addDays(today, 7); // 현재 날짜에 7일을 더한 날짜
const nextMonth = addMonths(today, 1); // 현재 날짜에 1개월을 더한 날짜
const nextYear = addYears(today, 1); // 현재 날짜에 1년을 더한 날짜

// 날짜 차이 계산
const daysDiff = differenceInDays(tomorrow, today); // 두 날짜 사이의 일 수 차이
const monthsDiff = differenceInMonths(nextMonth, today); // 두 날짜 사이의 개월 수 차이
const yearsDiff = differenceInYears(nextYear, today); // 두 날짜 사이의 연 수 차이

// 날짜 포맷팅
const formattedDate = format(today, 'yyyy-MM-dd'); // 현재 날짜를 yyyy-MM-dd 형식으로 포맷팅
const formattedDateTime = format(today, 'yyyy-MM-dd HH:mm:ss'); // 현재 날짜와 시간을 yyyy-MM-dd HH:mm:ss 형식으로 포맷팅

// 날짜 비교
const isTomorrowAfterToday = isAfter(tomorrow, today); // 내일이 오늘보다 이후인지 확인
const isNextWeekBeforeToday = isBefore(nextWeek, today); // 다음 주가 오늘보다 이전인지 확인
const isSameDate = isSameDay(tomorrow, nextWeek); // 두 날짜가 동일한 날짜인지 확인

// 날짜 유효성 검사
const isValidDate = isValid(parseISO('2022-01-01')); // '2022-01-01'이 유효한 날짜인지 확인

// 날짜 시간 조작
const startOfDayDate = startOfDay(today); // 현재 날짜의 시작 시간 (00:00:00)으로 설정
const startOfMonthDate = startOfMonth(today); // 현재 날짜의 월의 첫 날로 설정
const startOfYearDate = startOfYear(today); // 현재 날짜의 연도의 첫 날로 설정

console.log('Today:', today);
console.log('Tomorrow:', tomorrow);
console.log('Next Week:', nextWeek);
console.log('Next Month:', nextMonth);
console.log('Next Year:', nextYear);

console.log('Days Difference:', daysDiff);
console.log('Months Difference:', monthsDiff);
console.log('Years Difference:', yearsDiff);

console.log('Formatted Date:', formattedDate);
console.log('Formatted Date and Time:', formattedDateTime);

console.log('Is Tomorrow After Today:', isTomorrowAfterToday);
console.log('Is Next Week Before Today:', isNextWeekBeforeToday);
console.log('Is Same Date:', isSameDate);

console.log('Is Valid Date:', isValidDate);

console.log('Start of Day:', startOfDayDate);
console.log('Start of Month:', startOfMonthDate);
console.log('Start of Year:', startOfYearDate);

 이와 같이 다양한 함수를 통해  현재의 날짜와 시간을 계산했고, style-components와 map 함수를 통해 날짜를 나열하도록 하여 달력을 완성하고자 하였다. 

 

한국 서버 시간으로 연동하기

프로젝트나 서비스 사용자의 대상이 한국인이었기에 date-fns의 모든 함수와 기능에 대해 한국 시간으로 포맷이 필요했다. 기본적인 date-fns의 서버 시간은 미국 시간이니 꼭 체크할 필요가 있다. 

한국 시간으로 연동하는 방법은 날짜를 포맷시에 lacale 함수를 통해 포맷 시간을 한국 시간으로 설정하면 된다. 아래 코드에 한국 서버 시간으로 포매팅하는 예시 코드를 넣어두었다. 

import { ko } from "date-fns/locale";

// 현재 날짜와 시간을 가져옵니다.
const today = new Date();

// 한국 시간으로 날짜를 포맷합니다.
const formattedDate = format(today, "yyyy-MM-dd HH:mm:ss", { locale: ko });

// 포맷된 날짜를 콘솔에 출력합니다.
console.log("Formatted Date:", formattedDate);

 

date-fns와 Style-components를 활용한 커스텀 달력에 대해서는 다음편에서 공개하도록 하겠습니다. 

모두 화이팅 :)

2023.07.06 - [코딩/Javascript] - [React] date-fns와 Style-Components로 커스텀하기 쉬운 달력 만들기(2편)

 

[React] date-fns와 Style-Components로 커스텀하기 쉬운 달력 만들기(2편)

저번 1편에 이어서 2편으로 date-fns와 Style-Components로 커스텀 달력 편을 마무리 하고자 합니다! 2023.07.06 - [코딩/Javascript] - [React] date-fns와 style-components로 커스텀 달력 만들기(1편) [React] date-fns와 style

quddkflty.tistory.com

 

728x90
반응형