붉은거위 노트 (redgoose note)

특정 날짜에 속한 일주일의 날짜를 배열로 가져오기

Nest
Development
Category
Javascript
Hit
414
Star
1

일주일 날짜를 뽑아오는 코드가 필요해서 좀 고민하고 구글링도 해봤는데 해결이 잘 안나서 ChatGPT에게 물어봤더니 해법을 알려줬다. 유레카~
답변받은 코드를 참고하여 어떻게 작성할 수 있는지 힌트를 얻었다. ㅠㅠ

내용은 다음과 같다.


To get a list of the dates for the week containing a given date using JavaScript, you can use the following code:

function getDatesInWeek(date) {
  const weekStart = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
  const dates = [];
  const dayMs = 86400000; // number of milliseconds in a day
  for (let i = 0; i < 7; i++) {
    const date = new Date(weekStart.getTime() + dayMs * i);
    dates.push(date);
  }
  return dates;
}

const date = new Date("2022-01-05"); // date to find the week for
const dates = getDatesInWeek(date);
console.log(dates); // logs an array of dates for the week containing the given date

This code defines a function getDatesInWeek that takes a date as an argument. It first calculates the start date for the week by using the getFullYear, getMonth, getDate, and getDay methods of the Date object to find the year, month, day, and day of the week for the given date. It then uses a loop to create an array of dates for the week by incrementing the start date by one day for each iteration of the loop.

You can use this function to get the dates for the week containing any date by passing in a JavaScript Date object as the argument.


다음은 dayjs로 컨버팅 했다.

function getDatesInWeek(date) {
  const weekStart = dayjs()
    .year(date.year())
    .month(date.month())
    .day(date.date() - date.day())
    .hour(0)
    .minute(0)
    .second(0)
  const dates = []
  for (let i = 0; i < 7; i++) {
    const date = weekStart.add(i, 'day')
    dates.push(date)
  }
  return dates
}