Search code examples
javascriptarraysmomentjsmoment-timezone

Using moments js to create a date array


Does anyone know how i can use moment js , to create a dynamic dates array , that contains todays date and dates of next 9 days.

so im creating a scheduler that will run on some days(not yet specified) when it runs its supposed to prepare some reports on todays date and next 9 days, my idea is to create an array of dates and map through them but i cant figure out how to create such an array using moment js , any ideas ?

i checked some legacy code and they are using the following to get present date

const now = moment().add(-moment().utcOffset(), 'minutes').toDate()

Solution

  • I think this is a good candidate for a traditional for loop solution, using an offset and the moment .add method to build an array adding the offset as you go, ending up with a ten-day array where the first element at index 0 holds the value of your now variable.

    const moment = require('moment')
    
    const date = moment().add(-moment().utcOffset(), 'minutes').toDate()
    
    const reportDates = [];
    
    for (let dayOffset = 0; dayOffset < 10; dayOffset++) {
        const nextDate = moment(date).add(dayOffset, 'days').toDate();
        reportDates.push(nextDate)
    }
    
    console.log(reportDates)
    

    Output when I ran this snippet on my machine (@ ~10:22 Central US time):

    [
      2022-11-29T22:22:51.788Z,
      2022-11-30T22:22:51.788Z,
      2022-12-01T22:22:51.788Z,
      2022-12-02T22:22:51.788Z,
      2022-12-03T22:22:51.788Z,
      2022-12-04T22:22:51.788Z,
      2022-12-05T22:22:51.788Z,
      2022-12-06T22:22:51.788Z,
      2022-12-07T22:22:51.788Z,
      2022-12-08T22:22:51.788Z
    ]
    

    The moment.js vs other libraries is another discussion, and if at all possible to use a different library I would recommend date-fns to avoid any confusion in the future from the mutability built into moment objects.

    Good luck!