Home > database >  Looking for a function that would loop 12 times and give me all dates of every single day of every s
Looking for a function that would loop 12 times and give me all dates of every single day of every s

Time:08-24

I'm trying to make a sort of calendar type situation. Would be used to input an amount of km driven everyday to keep track of mileage and stuff like that. So what i'm looking for is a function that would loop 12 times to give me every single date of every single month for the whole year.

I've come across the following function quite a lot.

function getAllDaysInMonth(year, month) {

    const date = new Date(year, month, 1);
    const dates = [];
    while (date.getMonth() === month) {
        dates.push(new Date(date));
        date.setDate(date.getDate()   1);
    }
    return dates;
}

but I can't seem to fully comprehend how I could tweak this so it doesnt just return every date of the current month. All help and feedback would be massively appreciated.

CodePudding user response:

function getAllDaysInYear(year) {

    const date = new Date(year, 0, 1);
    const dates = [];
    while (date.getFullYear() === year) {
        dates.push(new Date(date));
        date.setDate(date.getDate()   1);
    }
    return dates;
}

CodePudding user response:

You can leverage the existing getDaysInMonth function, calling it once for each month. The following uses a modified version:

// Return the number of days in a month given year, month
// Month is calendar month, i.e. 1=Jan, 2=Feb, etc.
function daysInMonth(year, month) {
  return new Date(year, month, 0).getDate(); 
}

// Return an array of Dates for each day of a given year, month
// Month is calendar month, i.e. 1=Jan, 2=Feb, etc.
function getAllDaysInMonth(year, month) {
  let dates = [];
  for (let i=1, dim=daysInMonth(year, month); i<=dim; i  ) {
    dates.push(new Date(year, month-1, i));
  }
  return dates;
}

// Return an array of Dates for each day of a given year
function getAllDaysInYear(year) {
  let dates = [];
  for (let i=1; i<=12; i  ) {
    dates.push(...getAllDaysInMonth(year, i));
  }
  return dates;
}

console.log(getAllDaysInYear(2022).map(d=>d.toDateString()));

You can also use a more efficient

  • Related