JavaScript/라이브러리

[JavaScript]Moment.js 대신 Day.js 사용

DevStory 2021. 12. 17.

Moment.js란?

Moment.js는 JavaScript에서 날짜 및 시간을 조작하고 작업하는데 도움이 되는 JavaScript 라이브러리입니다. Moment.js는 날짜 및 시간과 관련된 라이브러리 중에서 가장 오래되었으며, 많은 개발자들에게 사용되었지만, 현재 다음 두 가지 이유로 개발이 중단되었습니다.

  • Moment.js의 용량 문제
  • 너무 오래되어 신규 기능 추가가 어려움

Moment.js의 단점을 극복하기 위해 Day.js, Luxon.js, date-fns.js 등 여러 라이브러리들이 개발되었으며, 이번 포스팅에서는 Day.js 라이브러리에 대해 소개합니다.

 

Day.js란?

Day.js는 Moment.js의 축소 버전으로 동일한 API를 사용하며 용량은 Moment.js 파일의 2~3% 밖에 되지 않습니다.

☞ 공식 사이트 바로가기

https://github.com/you-dont-need/You-Dont-Need-Momentjs#brief-comparison

 


dayjs 객체 초기화

dayjs()에 빈 값을 전달하면 현재 날짜 및 시간 기준으로 dayjs 객체가 생성됩니다.

dayjs();

 

특정 날짜 및 시간을 기준으로 dayjs 객체를 생성하는 경우 Format String을 전달합니다.

dayjs('2020-12-12');
dayjs('2020-01-01 10:20:30');

dayjs 객체 Get + Set

▶ 시 / 분 / 초 / 밀리초

다음은 day 객체에서 시 / 분 / 초 / 밀리초를 가져오는 예제입니다. get() 함수를 사용하거나 Date 객체의 함수와 매핑되는 함수를 사용합니다.

// 시간 가져오기
dayjs().hour();
dayjs().get('hour');
dayjs().get('h');

// 분 가져오기
dayjs().minute();
dayjs().get('minute');
dayjs().get('m');

// 초 가져오기
dayjs().second();
dayjs().get('second');
dayjs().get('s');

// 밀리초 가져오기
dayjs().millisecond();
dayjs().get('millisecond');
dayjs().get('ms');

 

다음은 day 객체의 set() 함수를 사용하여 시 / 분 / 초 / 밀리초를 설정하는 예제입니다.

// 시간 설정
dayjs().set('h', 10);
dayjs().set('hour', 10);

// 분 설정
dayjs().set('m', 20);
dayjs().set('minute', 20);

// 초 설정
dayjs().set('s', 40);
dayjs().set('second', 40);

// 밀리초 설정
dayjs().set('ms', 100);
dayjs().set('millisecond', 100);

set() 함수의 첫 번째 인수는 단위를 두 번째 인수는 값을 설정합니다.

 

▶ 년 / 월 / 일 / 요일

다음은 day 객체에서 년 / 월 / 일 / 요일을 가져오는 예제입니다.

// 년 가져오기
dayjs().year());
dayjs().get('year');
dayjs().get('y');

// 월 가져오기
dayjs().month());
dayjs().get('month');
dayjs().get('M');

// 일 가져오기
dayjs().date());
dayjs().get('date');
dayjs().get('D');

// 요일 가져오기
// 일요일(0) ~ 토요일(6)
dayjs().day());
dayjs().get('day');
dayjs().get('d');

 

다음은 day 객체의 set() 함수를 사용하여 년 / 월 / 일 / 요일을 설정하는 예제입니다.

// 년도 설정
dayjs().set('y', 2020);
dayjs().set('year', 2020);

// 월 설정
dayjs().set('M', 5);
dayjs().set('month', 5);

// 일 설정
dayjs().set('D', 25);
dayjs().set('date', 25);

// 요일 설정
dayjs().set('d', 4);
dayjs().set('day', 4);

 

▶ 올해의 날 

dayOfYear() 함수를 사용하여 올해의 몇 번째 날짜인지 가져오거나 설정할 수 있습니다. dayOfYear() 함수를 사용하기 위해서는 DayOfYear 플러그인이 설치되어야 합니다.

// 가져오기
dayjs().dayOfYear(); 

// 설정하기
dayjs().dayOfYear(365);

 

▶ 올해의 주

week() 함수를 사용하여 올해의 몇 번째 주인지 가져오거나 설정할 수 있습니다. week() 함수를 사용하기 위해서는 weekOfYear 플러그인이 설치되어야 합니다.

// 가져오기
dayjs().dayOfYear(); 

// 설정하기
dayjs().dayOfYear(20);

 

▶ 월의 일 수

daysInMonth() 함수를 사용하여 해당 월의 일 수를 가져옵니다. 

dayjs('2020-01').daysInMonth();
dayjs('2020-02').daysInMonth();
dayjs('2020-03').daysInMonth();
dayjs('2020-04').daysInMonth();

 

▶ 연도의 주 수

isoWeeksInYear() 함수를 사용하여 해당 연도의 주 수를 가져옵니다. isoWeeksInYear() 함수를 사용하기 위해서는 isoWeeksInYear 플러그인이 설치되어야 합니다.

dayjs().isoWeeksInYear();
dayjs('2020-01').isoWeeksInYear();

 

▶ 날짜의 최대 및 최소

dayjs()로 이루어진 배열 또는 여러 인수에서 max() 함수를 사용하여 날짜의 최댓값, min() 함수를 사용하여 날짜의 최솟값을 구합니다. minMax 플러그인이 설치되어야 합니다.

// 최대값
dayjs.max(dayjs(), dayjs('2018-01-01'), dayjs('2019-01-01'));
dayjs.max([dayjs(), dayjs('2018-01-01'), dayjs('2019-01-01')]);

// 최솟값
dayjs.min(dayjs(), dayjs('2018-01-01'), dayjs('2019-01-01'));
dayjs.min([dayjs(), dayjs('2018-01-01'), dayjs('2019-01-01')]);

dayjs 객체 조작하기

▶ 날짜 및 시간 더하기, 빼기

dayjs 객체에 날짜 및 시간을 더하는 경우 add() 함수를 사용하며 빼는 경우에는 substract() 함수를 사용합니다.

// 년도 더하기, 빼기
dayjs().add(1, 'year');
dayjs().substract(1, 'year');

// 월 더하기, 빼기
dayjs().add(1, 'month');
dayjs().substract(1, 'month');

// 일 더하기, 빼기
dayjs().add(1, 'day');
dayjs().substract(1, 'day');

// 시간 더하기, 빼기
dayjs().add(1, 'hour');
dayjs().substract(1, 'hour');

// 분 더하기, 빼기
dayjs().add(1, 'minute');
dayjs().substract(1, 'minute');

// 초 더하기, 빼기
dayjs().add(1, 'second');
dayjs().substract(1, 'second');

add() 함수와 substract() 함수의 첫 번째 인수는 단위를 두 번째 인수는 값을 설정합니다.

 

 

▶ dayjs 객체의 시작 시간 또는 시작 날짜

startOf() 함수는 dayjs 객체의 시작 시간 또는 시작 날짜를 반환합니다. 인수로 시작 부분의 단위를 설정합니다.

dayjs('2021-02-05 06:20:50').startOf('year');
// 2021-01-01 12:00:00 

dayjs('2021-02-05 06:20:50').startOf('month');
// 2021-02-01 12:00:00

dayjs('2021-02-05 06:20:50').startOf('day');
// 2021-02-05 12:00:00

dayjs('2021-02-05 06:20:50').startOf('hour');
// 2021-02-05 06:00:00

dayjs('2021-02-05 06:20:50').startOf('minute');
// 2021-02-05 06:20:00

dayjs('2021-02-05 06:20:50').startOf('second');
// 2021-02-05 06:20:50

 

▶ dayjs 객체의 마지막 시간 또는 마지막 날짜

endOf() 함수는 dayjs 객체의 마지막 시간 또는 마지막 날짜를 반환합니다. 인수로 마지막 부분의 단위를 설정합니다.

dayjs('2021-02-05 06:20:50').endOf('year');
// 2021-12-31 11:59:59

dayjs('2021-02-05 06:20:50').endOf('month');
// 2021-02-28 11:59:59

dayjs('2021-02-05 06:20:50').endOf('day');
// 2021-02-05 11:59:59

dayjs('2021-02-05 06:20:50').endOf('hour');
// 2021-02-05 06:59:59

dayjs('2021-02-05 06:20:50').endOf('minute');
// 2021-02-05 06:20:59

dayjs('2021-02-05 06:20:50').endOf('second');
// 2021-02-05 06:20:50

dayjs 객체 Format 및 출력 방법

▶ Format

format() 함수를 사용하여 dayjs 객체를 지정된 형식으로 Formatting 된 날짜 문자열을 반환합니다. 더 많은 Format을 사용하기 위해서는 advancedFormat 플러그인이 설치되어야 합니다.

dayjs().format('YYYY-MM-DD hh:mm:ss');
dayjs().format('DD/MM/YYYY');

 

▶ 차이 값

diff() 함수를 사용하여 주어진 날짜 사이의 차이 값을 얻습니다. 첫 번째 인수를 생략하면 밀리초 단위로 값을 반환하며, 밀리초 단위가 아닌 차이 값을 받기 위해서는 두 번째 인수에 단위를 전달합니다.

소수점 숫자도 원하는 경우 세 번째 인수로 true를 전달합니다.

dayjs('2020-12-31').diff('2020-01-01', 'day');
// 365

dayjs('2020-012-31').diff(dayjs('2020-01-01', 'day'));
// 365

dayjs 객체의 판별식(이전 / 동일함 / 이후 / 사이 / 윤년 / Date 객체 ) 

▶ 이전인지

isBefore() 함수로 이전 날짜인지 확인합니다.

dayjs('2020–01–15').isBefore('2020–01–01');
// false

dayjs('2020–01–15').isBefore('2020–01–30');
// true

 

▶ 동일한지

isSame() 함수로 두 날짜가 동일한지 확인합니다.

dayjs('2020–01–15').isSame('2020–01–15');
// true

dayjs('2020–01–15').isSame('2020–01–30');
// false

 

▶ 이후인지

isAfter() 함수로 이후 날짜인지 확인합니다.

dayjs('2020–01–15').isAfter('2020–01–01');
// true

dayjs('2020–01–15').isAfter('2020–01–30');
// false

 

▶ 두 날짜 사이인지 

isBetween() 함수를 사용하여 dayjs의 객체가 둘 날짜 사이에 존재하는지 확인합니다. isBetween() 함수를 사용하기 위해서는 isBetween 플러그인이 설치되어야 합니다.

dayjs('2020–01–15').isBetween('2020–01–01', '2020-01-30');
// true

dayjs('2020–01–15').isBetween('2020–01–20', '2020-01-30');
// false

 

▶ 윤년인지

isLeapYear() 함수를 사용하여 dayjs의 객체가 윤년인지 확인합니다. isLeapYear() 함수를 사용하기 위해서는 isLeapYear 플러그인이 설치되어야 합니다.

dayjs('2020-01-01').isLeapYear();
// true

 

▶ Date 객체인지

isValid() 함수를 사용하여 dayjs 객체에 할당된 값이 Date 객체인이 확인합니다.

dayjs(new Date()).isValid();
// true
반응형

'JavaScript > 라이브러리' 카테고리의 다른 글

[JavaScript]Moment.js 사용 방법  (1) 2021.12.16

댓글