본문 바로가기
개발/Javascript

Javascript Date compare

by 혈중마라농도 2022. 1. 25.
// -1 : adate가 작음, 0: 같음, 1: adate가 큼
function compareDate(adate, bdate) {
  // 연도, 월, 일, 시, 분 순서대로 비교
  if (adate.getFullYear() !== bdate.getFullYear()) {
    return adate.getFullYear() < bdate.getFullYear() ? -1 : 1;
  }
  if (adate.getMonth() !== bdate.getMonth()) {
    return adate.getMonth() < bdate.getMonth() ? -1 : 1;
  }
  if (adate.getDate() !== bdate.getDate()) {
    return adate.getDate() < bdate.getDate() ? -1 : 1;
  }
  if (adate.getHours() !== bdate.getHours()) {
    return adate.getHours() < bdate.getHours() ? -1 : 1;
  }
  if (adate.getMinutes() !== bdate.getMinutes()) {
    return adate.getMinutes() < bdate.getMinutes() ? -1 : 1;
  }

  // 모두 같으면 0 반환
  return 0;
}

 

반응형

댓글