skip to Main Content

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!

4

Answers


  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));
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. 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);
    Login or Signup to reply.
  4. 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);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search