- 자바스크립트에서 두 날짜 사이 비교하기
Date 객체의 getTime() 메서드를 사용하면 해당 시간을 밀리초 단위로 환산하게 된다.
이 메서드를 활용하면 두 날짜를 비교할 수 있다.
- 초 : 1000
- 분 : 1000 * 60
- 시 : 1000 * 60 * 60
- 일 : 1000 * 60 * 60 * 24
- 월 : 1000 * 60 * 60 * 24 * 30
- 년 : 1000 * 60 * 60 * 24 * 365
// 일 차이 구하기
const getDateDiff = (d1, d2) => {
const date1 = new Date(d1);
const date2 = new Date(d2);
const diffDate = date1.getTime() - date2.getTime();
return Math.abs(diffDate / (1000 * 60 * 60 * 24));
// Math.abs()를 사용하는 이유는 d1, d2의 순서가 바뀌어 음수가 나올 때도 양수로 변환시켜 주기 위함이다.
}
// 월 차이 구하기
const getMonthDiff = (d1, d2) => {
const date1 = new Date(d1);
const date2 = new Date(d2);
const diffDate = date1.getTime() - date2.getTime();
return Math.floor(Math.abs(diffDate / (1000 * 60 * 60 * 24 * 30)));
}
// 연도 차이 구하기
const getYearDiff = (d1, d2) => {
const date1 = new Date(d1);
const date2 = new Date(d2);
const diffDate = date1.getTime() - date2.getTime();
return Math.floor(Math.abs(diffDate / (1000 * 60 * 60 * 24 * 365)));
}
// 출력 결과
getDateDiff("2023-09-01", "2023-10-01"); // 30
getMonthDiff("2023-06-01", "2023-10-01"); // 4
getYearDiff("2001-10-01", "2023-10-01"); // 22
- 참고자료
[JS] 두 날짜 사이의 일수 구하기
코드 const getDateDiff = (d1, d2) => { const date1 = new Date(d1); const date2 = new Date(d2); const diffDate = date1.getTime() - date2.getTime(); return Math.abs(diffDate / (1000 * 60 * 60 * 24)); // 밀리세컨 * 초 * 분 * 시 = 일 } getDateDiff("2
gurtn.tistory.com