주차 구하기

Written on September 16, 2019

일요일을 한 주의 시작으로 주차를 구하는 방법

const getWeeksInMonth = inputDate => {
  let year = inputDate.getFullYear();
  let month = inputDate.getMonth();
  let firstDate = new Date(year, month, 1);
  let lastDate = new Date(year, month + 1, 0);
  let firstWeekDay = firstDate.getDay();
  let lastWeekDay = lastDate.getDay();
  let weeksInMonth = Math.ceil((firstWeekDay - 1 + lastDate.getDate()) / 7);
  if (lastWeekDay === 0 || lastWeekDay === 1 || lastWeekDay === 2) {
    weeksInMonth -= 1;
  }
  return weeksInMonth;
};

const weekNumberBySunday = inputDate => {
  let year = inputDate.getFullYear();
  let month = inputDate.getMonth();
  let date = inputDate.getDate();
  let firstDate = new Date(year, month, 1);
  let lastDate = new Date(year, month + 1, 0);
  let firstWeekDay = firstDate.getDay();
  let lastWeekDay = lastDate.getDay();
  let offsetDate = date + firstWeekDay - 1;
  let weeksInMonth = Math.ceil((firstWeekDay - 1 + lastDate.getDate()) / 7);
  if (lastWeekDay === 0 || lastWeekDay === 1 || lastWeekDay === 2) {
    weeksInMonth -= 1;
  }
  let index = 1;
  if (firstWeekDay === 4 || firstWeekDay === 5 || firstWeekDay === 6) {
    index = 0;
  }
  let week = Math.floor(offsetDate / 7) + index;
  if (week === 0) {
    week = getWeeksInMonth(new Date(year, month, 0));
    return { month: month - 1, week };
  }
  return week <= weeksInMonth ? { month, week } : { month: month + 1, week };
};

결과 값은 { "month": 8, "week": 3 } 형태이다.


관련 post

👩🏻‍💻 배우는 것을 즐기는 프론트엔드 개발자 입니다
부족한 블로그에 방문해 주셔서 감사합니다 🙇🏻‍♀️

in the process of becoming the best version of myself