Language/React

React/moment 사용 탐방

건담아빠 2022. 10. 21. 11:44

앞으로 자주쓸것 같기도 하고 한번에 분석 끝내놓고 나중에 찾아보는 시간을 줄이기 위해서 작성해 둔다.

 

module 추가

$ yarn add moment

https://yarnpkg.com/package/moment

 

https://yarnpkg.com/package/moment

Fast, reliable, and secure dependency management.

yarnpkg.com

 

기본 사용 방법

import moment from 'moment';

...
console.log(moment().format('YYYYMMDD'));
console.log(moment().subtract(1, 'days').endOf('day'));
...

 

예시)

diff 예시

const diffDaysToText = (compareDt, baseDt) => {
  const diffDays = compareDt.diff(baseDt, 'days');
  console.log(`diffDays : ${diffDays} / type : ${typeof diffDays}`);

  if (diffDays < 0) {
    return `${Math.abs(diffDays)}일전`;
  } else if (diffDays > 0) {
    return `${Math.abs(diffDays)}일후`;
  } else {
    return '오늘';
  }
};

# `2022-10-19`는 `2022-10-21`를 기준으로 이틀에 있다.
console.log(diffDaysToText(moment('2022-10-19'), moment('2022-10-21')));
  >> 2일전

console.log(diffDaysToText(moment('2022-10-20'), moment('2022-10-21')));
  >> 1일전

console.log(diffDaysToText(moment('2022-10-21'), moment('2022-10-21')));
  >> 오늘
  
console.log(diffDaysToText(moment('2022-10-21'), moment()));
  >> 오늘
  
console.log(diffDaysToText(moment('2022-10-22'), moment('2022-10-21')));
  >> 1일후

 

날짜생성 - moment()

moment().format();
  > 2022-10-21T13:19:11+09:00
  
moment('2022-10-21').format();
  > 2022-10-21T00:00:00+09:00

moment('2022-10-21', 'YYYY.MM.DD').format();
  > 2022-10-21T00:00:00+09:00
  
moment('10/21/22', 'MM/DD/YY').format();
  > 2022-10-21T00:00:00+09:00
  
moment('2022-10-21 13:10:22', 'YYYY-MM-DD HH:mm:ss').format();
  > 2022-10-21T10:10:22+09:00

 

형식 - format()

const now = moment();
now.format();
  > 2022-10-21T13:23:06+09:00
  
now.format('YY-MM-DD');
  > 22-10-21
  
now.format('YYYY/MM/DD HH:mm!ss');
  > 2022/10/21 13:23!06
  
moment('20220922').format('YYYY-MM-DD')
  > 2022-09-22
  
moment('20220902').format('YYYY-M-D')
  > 2022-9-2

moment('20220902').format('YYYY-M-DD')
  > 2022-9-02

 

윤년 확인 - isLeapYear()

moment().isLeapYear();
  >> false
  
moment([2020]).isLeapYear();
  >> true
  
moment([2019]).isLeapYear();
  >> false

 

날짜 지정 단위에 따른 시작 종료 - startOf(), endOf()

const now = moment('2022-10-21 12:10:15', 'YYYY-MM-DD HH:mm:ss');

now.format();
  >> 2022-10-21T12:10:15+09:00

# 일자 기준 시작
now.startOf('day').format();
  >> 2022-10-21T00:00:00+09:00

# 일자 기준 종료
now.endOf('day').format();
  >> 2022-10-21T23:59:59+09:00

# 년 기준 시작
now.startOf('year').format();
  >> 2022-01-01T00:00:00+09:00

# 년 기준 종료
now.endOf('year').format();
  >> 2022-12-31T23:59:59+09:00

# 시간 기준 시작
now.startOf('hour').format();
  >> 2022-12-31T23:00:00+09:00

# 시간 기준 종료
now.endOf('hour').format();
  >> 2022-12-31T23:59:59+09:00

# 분 기준 시작
now.startOf('minute').format();
  >> 2022-12-31T23:59:00+09:00

# 분 기준 종료
now.endOf('minute').format();
  >> 2022-12-31T23:59:59+09:00

 

날짜 및 시간 더하기 - add()

const now = moment('2022-10-21 13:41:58', 'YYYY-MM-DD HH:mm:ss');

now.add(1, 'years').format();
now.add(1, 'y').format();
  >> 2023-10-21T13:41:58+09:00

now.add(1, 'months').format();
now.add(1, 'm').format();
  >> 2022-11-21T13:41:58+09:00

now.add(1, 'weeks').format();
now.add(1, 'w').format();
  >> 2022-10-28T13:41:58+09:00

now.add(1, 'days').format();
now.add(1, 'd').format();
  >> 2022-10-22T13:41:58+09:00

now.add(1, 'hours').format();
now.add(1, 'h').format();
  >> 2022-10-21T14:41:58+09:00

now.add(1, 'minutes').format();
now.add(1, 'm').format();
  >> 2022-10-21T13:42:58+09:00

now.add(1, 'seconds').format();
now.add(1, 's').format();
  >> 2022-10-21T13:41:59+09:00

now.add(1000, 'milliseconds').format();
now.add(1000, 'ms').format();
  >> 2022-10-21T13:41:59+09:00

 

날짜 및 시간 빼기 - subtract()

now.subtract(1, 'years').format();
now.subtract(1, 'y').format();
  >> 2021-10-21T12:10:15+09:00

now.subtract(1, 'months').format();
now.subtract(1, 'm').format();
  >> 2020-09-21T12:10:15+09:00

now.subtract(1, 'weeks').format();
now.subtract(1, 'w').format();
  >> 2020-08-07T12:10:15+09:00

now.subtract(1, 'days').format();
now.subtract(1, 'd').format();
  >> 2020-08-05T12:10:15+09:00

now.subtract(1, 'hours').format();
now.subtract(1, 'h').format();
  >> 2020-08-05T11:10:15+09:00

now.subtract(1, 'minutes').format();
now.subtract(1, 'm').format();
  >> 2020-08-05T10:09:15+09:00
  
now.subtract(1, 'seconds').format();
now.subtract(1, 's').format();
  >> 2020-08-05T10:08:14+09:00

now.subtract(1000, 'milliseconds').format();
now.subtract(1000, 'ms').format();
  >> 2020-08-05T10:08:12+09:00

 

날짜 및 시간 차이 구하기 - deff()

const oldDt = moment('2019-10-21 12:10:15', 'YYYY-MM-DD HH:mm:ss');
const compareDt = moment('2022-05-10 11:20:45', 'YYYY-MM-DD HH:mm:ss');

compareDt.diff(oldDt);
  >> 80521830000
  
compareDt.diff(oldDt, 'years');
  >> 2
  
compareDt.diff(oldDt, 'months');
  >> 30
  
compareDt.diff(oldDt, 'weeks');
  >> 133
  
compareDt.diff(oldDt, 'days');
  >> 931
  
compareDt.diff(oldDt, 'hours');
  >> 22367
  
compareDt.diff(oldDt, 'minutes');
  >> 1342030
  
compareDt.diff(oldDt, 'seconds');
  >> 80521830
  
compareDt.diff(oldDt, 'milliseconds');
  >> 80521830000

 

현재 날짜 및 시간을 기준으로 상대적인 시간 구하기 - fromNow()

  const now = moment('2022-10-21 12:10:15', 'YYYY-MM-DD HH:mm:ss');
  now.fromNow();
    >> 2시간 전
  now.startOf('day').fromNow();
    >> 14시간 전
  now.endOf('day').fromNow();
    >> 10시간 후
  
  moment('2022-10-19').fromNow();
    >> 3일 전
  moment('2022-10-20').fromNow();
    >> 2일 전
  moment('2022-10-21').fromNow();
    >> 14시간 전

 

지정한 날짜 및 시간을 기준으로 상대적인 시간 구하기 - from()

const fromDt = moment('2022-10-19 10:23:09', 'YYYY-MM-DD HH:mm:ss');
const toDt = moment('2022-10-21 12:10:15', 'YYYY-MM-DD HH:mm:ss');

toDt.from(fromDt);
  >> 2일 후

toDt.startOf('day').from(fromDt);
  >> 2일 후

toDt.endOf('day').from(fromDt);
  >> 3일 후

moment().from(fromDt);
  >> 2일 후

 

날짜가 지정한 시간 단위에서 특정 날짜와 일치하는지 구하기 - isSame()

const fromDt = moment('2022-10-19 10:23:09', 'YYYY-MM-DD HH:mm:ss');
const toDt = moment('2022-10-21 12:10:15', 'YYYY-MM-DD HH:mm:ss');

fromDt.isSame(moment('2022-10-19 10:23:09', 'YYYY-MM-DD HH:mm:ss'));
  >> true
  
fromDt.isSame(toDt);
  >> false
moment('20221010').isSame(moment('20221010'));
  >> true

moment('20221010').isSame(moment('20221022'));
  >> false

 

특정 날짜의 `>=` OR `<=` 구하기 - isAfter(), isSameOrAfter(),  isBefore(), isSameOrBefor(), 

# isBefore, isSameOrBefore
moment('2022-10-19').isBefore('2022-10-19');
  >> false

moment('2022-10-19').isSameOrBefore('2022-10-19');
  >> true
  
moment('2022-10-21').isBefore('2022-10-20');
  >> false
  
moment('2022-10-21').isSameOrBefore('2022-10-21');
  >> true

# isAfter, isSameOrAfter
moment('2022-10-19').isAfter('2022-10-19');
  >> false
  
moment('2022-10-19').isSameOrAfter('2022-10-19');
  >> true
  
moment('2022-10-21').isAfter('2022-10-20');
  >> true
  
moment('2022-10-21').isSameOrAfter('2022-10-21');
  >> true

 

날짜가 특정 날짜들 사이에 있는지 구하기 - isBetween()

undefined 는 오늘 날짜로 대체 됨

moment('2022-10-19').isBetween('2022-10-09', '2022-10-15');
  >> false
moment('2022-10-19').isBetween('2022-10-09', '2022-10-22');
  >> true

moment('2022-10-19').isBetween('2022-10-09', undefined);
  >> true
moment('2022-10-19').isBetween('2022-10-09', undefined, '2022-10-22');
  >> true

moment('2022-10-19').isBetween('2022-10-09', null);
  >> false
moment('2022-10-19').isBetween('2022-10-09', null, '2022-10-22');
  >> false

moment('2022-10-19').isBetween('2022-10-09', '');
  >> false
moment('2022-10-19').isBetween('2022-10-09', '', '2022-10-22');
  >> false
  
  
  
// 대괄호는 '끝 포함'을 의미하고 괄호는 '끝 제외'를 의미
moment('2022-10-30').isBetween('2022-10-30', '2022-12-30', null, '()');
  >> false
moment('2022-10-30').isBetween('2022-10-30', '2022-12-30', null, '[)');
  >> true
moment('2022-10-30').isBetween('2022-01-01', '2022-10-30', null, '()');
  >> false
moment('2022-10-30').isBetween('2022-01-01', '2022-10-30', null, '(]');
  >> true
moment('2022-10-30').isBetween('2022-10-30', '2022-10-30', null, '[]');
  >> true

 

 

참조 블로그 및 moment사이트를 바탕으로 무작정 따라보기 해보았습니다.

 

 

 

참조) 

https://momentjs.com/docs/

 

Moment.js | Docs

moment.relativeTimeThreshold(unit); // getter moment.relativeTimeThreshold(unit, limit); // setter duration.humanize has thresholds which define when a unit is considered a minute, an hour and so on. For example, by default more than 45 seconds is consider

momentjs.com

https://velog.io/@dojunggeun/JavaScript-Moment.js%EB%A5%BC-%EC%9D%B4%EC%9A%A9%ED%95%98%EC%97%AC-Date-Time-%EA%B4%80%EB%A6%AC%ED%95%98%EA%B8%B0

 

[JavaScript] Moment.js를 이용하여 Date 다루기

자바스크립트에서 날짜, 시간을 다루는 것은 항상 번거롭다. 네이티브 date 메소드는 지저분하고 API는 일관성이 부족하다. 그래서 Stackoverlow에 date와 관련된 질문을 하면 "Moment.js를 쓰세요"라는

velog.io

https://jsikim1.tistory.com/195

 

moment.js 사용 방법 - JavaScript 날짜 라이브러리

moment.js 사용 방법 - JavaScript 날짜 라이브러리 moment.js는 JavaScript에서 사용되는 날짜관련 라이브러리 중 가장 많이 사용되었던 라이브러리입니다. 현재는 더이상의 업데이트가 없을 것이라

jsikim1.tistory.com