리액트 년월 차이 계산 자바스크립트
리액트 년월 차이 계산 자바스크립트
//시작일자, 종료일자 넣고 조회하는 함수
const getYearMonthDifference = (startDate, endDate) => {
const start = new Date(startDate);
const end = new Date(endDate);
let years = end.getFullYear() - start.getFullYear();
let months = end.getMonth() - start.getMonth();
// 만약 월 차이가 음수면, 연도에서 1을 빼고 월을 보정합니다.
if (months < 0) {
years -= 1;
months += 12;
}
return { years, months };
};
// 예제 사용
const { years, months } = getYearMonthDifference('2022-05-15', '2024-10-16');
console.log(`차이: ${years}년 ${months}개월`); // 출력: 차이: 2년 5개월
// date-fns 라이브러리로 더 직관적이고 깔끔하게 계산할 수 있습니다.
import { differenceInYears, differenceInMonths } from 'date-fns';
const getYearMonthDifference = (startDate, endDate) => {
const totalMonths = differenceInMonths(new Date(endDate), new Date(startDate));
const years = Math.floor(totalMonths / 12);
const months = totalMonths % 12;
return { years, months };
};
// 예제 사용
const { years, months } = getYearMonthDifference('2022-05-15', '2024-10-16');
console.log(`차이: ${years}년 ${months}개월`); // 출력: 차이: 2년 5개월
// Moment.js
import moment from 'moment';
const getYearMonthDifference = (startDate, endDate) => {
const start = moment(startDate);
const end = moment(endDate);
const years = end.diff(start, 'years');
const months = end.diff(start.add(years, 'years'), 'months');
return { years, months };
};
// 예제 사용
const { years, months } = getYearMonthDifference('2022-05-15', '2024-10-16');
console.log(`차이: ${years}년 ${months}개월`); // 출력: 차이: 2년 5개월