리액트 년월 차이 계산 자바스크립트
//시작일자, 종료일자 넣고 조회하는 함수
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개월 
'프로그램 > React-Native' 카테고리의 다른 글
| react의 for 대신 사용하는 .forEach 에서 validation (0) | 2024.11.28 | 
|---|---|
| 리액트 엑셀파일업로드 (같은 이름의 엑셀파일 재업로드) (1) | 2024.10.30 | 
| Missing "key" prop for element in iterator react/jsx-key (1) | 2024.09.14 | 
| nameSearch 에러 recognize the nameSearch prop on a DOM element (1) | 2024.09.11 | 
| date.isValid is not a function (1) | 2024.09.06 |