1

Sorry for the sloppily worded title, but here is an example of what I want to achieve:

//increment of 5
const daysOfMonthArray = [16, 21, 26, 31, 5, 10, 15, 20, 25, 30, 4, 9.....]

I'm having a hard time trying to find a good way to do this using dayJS, but I'm sure it's reasonably doable with JavaScript's built in date objects as well. Any help would be greatly appreciated, thanks!

Brenden Baio
  • 107
  • 8
  • What is the logic for determining the first day? Which is the month you start with? In which year? – trincot Jul 16 '23 at 11:19
  • The fundamental solution is provided by [*How can I add 1 day to current date?*](https://stackoverflow.com/questions/9989382/how-can-i-add-1-day-to-current-date) How you chose to loop for the required number of iterations and set the value to increment by is up to you. There are a huge number of possible solutions. – RobG Jul 18 '23 at 11:41

4 Answers4

1

Use Date::getDate() and Date::setDate() to manipulate the date part:

const dt = new Date;

const daysOfMonthArray = Array.from({length: 15}, (_, idx, date = dt.getDate()) => dt.setDate(date + 5) && date);

console.log(JSON.stringify(daysOfMonthArray));
Alexander Nenashev
  • 8,775
  • 2
  • 6
  • 17
1

You can use a generator function for this purpose:

function* getIncrementedDate(date, days) {
    while (true) {
        date = new Date(date);
        date.setDate(date.getDate() + days);
        yield date;
    }
}

const gen = getIncrementedDate(new Date(), 5);

let output = [];

for (let index = 0; index < 20; index++) {
    output.push(gen.next().value);
}

console.log(output);

Explanation: the generator function takes a date and a days parameter and (forever) adds the number of days to the date, always yielding the actual result.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
1

Here is a slight variation of the answer from Alexander, where the loop has no side-effects (on a variable dt):

const day = new Date().getDate();
const result = Array.from({length: 15}, (_, i) => 
    new Date(new Date().setDate(day + i*5)).getDate()
)
console.log(...result);
trincot
  • 317,000
  • 35
  • 244
  • 286
0

Use Array.from() to create an array with the specified length. The day value for each element is calculated in the mapping function by adding the starting day to the index multiplied by the increment.

const generateDaysArray = (startDate, increment, length) =>
  Array.from({ length }, (_, i) => new Date(startDate).getDate() + i * increment);

// usage example
const startDate = '2023-07-16';
const increment = 5;
const length = 24;

const daysOfMonthArray = generateDaysArray(startDate, increment, length);

console.log(daysOfMonthArray);