JavaScript 날짜계산(Moment.js 사용법 및 대안 - Day.js, Luxcon)

 

JavaScript 날짜계산(Moment.js 사용법 및 대안 - Day.js, Luxcon)

 

https://momentjs.com/

 

Moment.js | Home

Format Dates moment().format('MMMM Do YYYY, h:mm:ss a'); moment().format('dddd'); moment().format("MMM Do YY"); moment().format('YYYY [escaped] YYYY'); moment().format(); Relative Time moment("20111031", "YYYYMMDD").fromNow(); moment("20120620", "YYYYMMDD"

momentjs.com

 

 

 

Moment.js 는 JavaScript 의 날짜 및 시간 처리를 간편하게 만들 수 있는 라이브러리입니다.

DateRangePicker(bootstrap-daterangepicker)와 연동하여 설정할 수 있습니다.

https://www.daterangepicker.com/

 

Date Range Picker — JavaScript Date & Time Picker Library

Originally created for reports at Improvely, the Date Range Picker can be attached to any webpage element to pop up two calendars for selecting dates, times, or predefined ranges like "Last 30 Days". To get started, include jQuery, Moment.js and Date Range

www.daterangepicker.com

 


1. Moment.js 사용법, 사용 예제

 

CDN 추가 혹은 NPM Install, 공식사이트 JS 파일 다운로드

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
<script>
  console.log(moment().format());
</script>

 

doy와 dow

 - dow : 주의 시작 요일을 설정

 - doy :  연도의 첫 주에 포함되는 최소 날짜를 설정 ( ISO 8601 기준, 첫번 째 주는 최소 4일을 포함)

moment.updateLocale("en", {
  week: {
    dow: 1, // 주의 시작 요일을 월요일로 설정
    doy: 4, // 첫 주는 연도의 최소 4일을 포함해야 함
  },
});

 

dow, doy  의 설정에 따라 주차 계산 및 요일 반환에 영향을 미치므로 중요함.

ISO 8601 기준은 글로벌 표준이며, 지역(Locale) 설정을 통해 지역별로 규칙을 적용할 수 도 있다.

 

moment(); // 현재 
moment().format(); // 포맷 현재시간 출력

 

moment().format("YYYY-MM-DD"); // 2024-01-01

 

 

 

날짜 계산

add() 함수를 통해 추가를 하거나, subtract 함수를 통해 뺄 수 있다.

"days", "month", "years" 와 같은 옵션을 주어 원하는 일, 주, 년 날짜에 대해 더하거나 뺄 수 있다.

moment().add(7, "days"); // 7일 추가
moment().subtract(1, "month"); // 1개월 빼기

 

diff 함수를 통해서 두 날짜 사이의 차이를 계산할 수도 있음

const start = moment("2024-01-01");
const end = moment("2024-12-31");
end.diff(start, "days"); // 두 날짜 사이의 차이를 일 단위로 계산

 

날짜 및 시간 정보 관련 함수

moment().year(); // 연도 가져오기
moment().month(); // 월(0부터 시작)
moment().date(); // 일
moment().hour(); // 시
moment().minute(); // 분
moment().second(); // 초
moment().day(); // 요일(0: 일요일, 1: 월요일, ...)

 

ISO 기준에 대한 주차 함수

moment().isoWeek(); // ISO 주 가져오기
moment().isoWeekday(); // ISO 주 기준 요일 가져오기
moment().isoWeek(1).isoWeekday(1); // ISO 주와 요일 설정

 

 

날짜의 시작 혹은 끝을 계산하는 함수

moment().startOf("day"); // 하루의 시작 (00:00:00)
moment().endOf("month"); // 월의 끝 (23:59:59)

 

현재 주차와 주차 기준 연도

console.log(moment().week()); // 현재 주차
console.log(moment().weekYear()); // 현재 주차 기준 연도

 

 

특정 주차 계산

const weekStart = moment().week(10).startOf("week");
console.log(weekStart.format("YYYY-MM-DD")); // 10번째 주의 시작일

 

 

날짜 범위처리

월 시작일, 종료일 구하기

const rangeStart = moment().startOf("month");
const rangeEnd = moment().endOf("month");

console.log(rangeStart.format("YYYY-MM-DD")); // 월 시작일
console.log(rangeEnd.format("YYYY-MM-DD"));   // 월 종료일

 

 


 

2. Moment.Js를 권장하지 않은 이유

 

1.  라이브러리 크기

 

큰 파일 크기

 - Moment.js 는 매우 강력한 라이브러리이나, 그에 따른 라이브러리 크기가 큰 편입니다. 

 - 일반적으로 67KB 정도(압축 시 16~18KB) / 현대적인 애플리케이션 성능 최적화 측면에서 부담이 됨

 - 대안인 Day.js, date-fns는 이보다 더 경량의 라이브러리

 

2. Deprecation, 기능 추가 중단됨

 

https://momentjs.com/docs/#/-project-status/

 

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

We now generally consider Moment to be a legacy project in maintenance mode. It is not dead, but it is indeed done.
In practice, this means:
We will not be adding new features or capabilities.We will not be changing Moment's API to be immutable.We will not be addressing tree shaking or bundle size issues.We will not be making any major changes (no version 3).We may choose to not fix bugs or behavioral quirks, especially if they are long-standing known issues.

 

3. 불변성 (Immutabel)

 

Moment.js는 객체가 변경 가능한(Mutable) 방식으로 설계되었음.

즉, ADD나 SUBTRACT 등의 메서드가 원본 객체를 수정함.

 


 

3. Moment.Js 의 대체, 대안

 

 

Lxxon

moment.js 후속 프로젝트로 더 나은 시간대와 국제화 지원을 제공

https://moment.github.io/luxon/#/

 

luxon - Immutable date wrapper

 

moment.github.io

 

Day.js 

Moment.js와 API가 거의 동일하지만 크기가 훨씬 작고, 불변성을 지원함. 

일부 기능은 별도로 구현할 필요가 있음.

 

https://day.js.org/

 

Day.js · 2kB JavaScript date utility library

2kB JavaScript date utility library

day.js.org

 

이외

date-fns, js-Joda 등 라이브러리를 사용하거나

현대 브라우저의 경우, 기본 DATE 기능이 향상되어 대체 보완 가능함( Intl.DateTimeFormat, Temporal API)

 

 

결론 

이미 오래된, 기존에 구현한 프로젝트의 경우, Moment.js를 통한 날짜 계산을 활용했을 가능성이 높다.

바로 전환할 필요성은 없겠으나 점진적으로 대안 라이브러리 등을 적용해보는 게 좋다.