[javascript] 특정 날짜의 해당 월의 모든 주의 시작일과 종료일 구하기

특정 날짜의 해당 월의 모든 주의 시작일과 종료일을 JavaScript를 사용하여 구하는 방법에 대해 알아보겠습니다.

날짜를 입력받고 해당 월의 첫 날과 마지막 날 구하기

먼저, 주어진 날짜를 사용하여 해당하는 월의 첫 번째 날과 마지막 날을 구하는 JavaScript 코드입니다.

const date = new Date('2022-10-15');
const firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
const lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);

위의 코드에서 date에는 특정 날짜가 포함되어 있습니다. getYear()를 사용하여 년도를, getMonth()를 사용하여 월을, 그리고 getDate()를 사용하여 일을 가져올 수 있습니다. new Date()를 사용하여 새로운 Date 개체를 만들고, 이를 통해 해당 월의 첫 번째 날(firstDay)과 마지막 날(lastDay)을 구할 수 있습니다.

주의 시작일과 종료일 구하기

이제 해당 월의 모든 주의 시작일과 종료일을 구하는 코드를 살펴보겠습니다.

function getWeekday(date) {
  const day = date.getDay();
  return day === 0 ? 7 : day;
}

function getStartAndEndDatesForMonth(date) {
  const firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
  const lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
  const firstWeekday = getWeekday(firstDay);
  const result = [];
  let currentDay = firstDay;

  while (currentDay <= lastDay) {
    const startDate = new Date(currentDay);
    const endDate = new Date(currentDay);
    endDate.setDate(currentDay.getDate() + (6 - getWeekday(currentDay) + 1));
    result.push({ start: startDate, end: endDate });
    currentDay.setDate(currentDay.getDate() + (7 - getWeekday(currentDay) + 1));
  }

  return result;
}

const dates = getStartAndEndDatesForMonth(date);
console.log(dates);

위의 코드에서 getWeekday 함수는 주어진 날짜의 요일을 반환합니다. 그리고 getStartAndEndDatesForMonth 함수는 주어진 날짜에 해당하는 월의 시작일과 종료일을 찾고, 해당 월의 모든 주의 시작일과 종료일을 배열에 추가하여 반환합니다.

이를 통해 dates 배열에는 주의 시작일과 종료일이 포함된 객체들이 들어가게 됩니다.

이제 위의 두 단계를 통해 특정 날짜의 해당 월의 모든 주의 시작일과 종료일을 구하는 방법을 살펴보았습니다. 해당 코드를 사용하여 간단하게 날짜 데이터를 처리하고 활용할 수 있게 되었습니다.

참고: