Home > other >  Push a date to an array with moment js nodejs
Push a date to an array with moment js nodejs

Time:10-30

I'm writing a function in NodeJs in which getting 2 dates returns an array with all dates in the range. Instead, I'm getting an array that adds to it the same date and deletes itself every time.

For example: Getting start date 1/11/2026 and end date 3/11/2026 it should return [1/11/2026, 2/11/2026, 3/11/2026] now it does: [1/11/2026],[2/11/2026, 2/11/2026],[3/11/2026, 3/11/2026, 3/11/2026]

I tried moving out from the while the format but I turn it to string I tried having 2 arrays and use spread operator but didn't succeed

Here is my code:

const dateList = ({ start, end }) => {
    let now = moment(start);
    const end = moment(end);
    let dates = [];
    while (now.format('YYYY-MM-DD') <= end.format('YYYY-MM-DD')) {
        dates.push(now);
        now = now.add(1, 'days');
    }
    return dates;
}

CodePudding user response:

Moment use instance of object

your variable now is an instance of moment date so if you you push it in your array and set his day to 1 the instance in your array get this change too because it's the same instance. You need to push a clone of your moment instance.

const dateList = ({ start, end }) => {
    let now = moment(start);
    const end = moment(end);
    let dates = [];
    while (now.format('YYYY-MM-DD') <= end.format('YYYY-MM-DD')) {
        dates.push(now.clone());
        now = now.add(1, 'days');
    }
    return dates;
}

and you can use moment query to test if end is after now.

while(now.format('YYYY-MM-DD') <= end.format('YYYY-MM-DD')) => while(now.isSameOrBefore(end))

final code :

const dateList = ({ start, end }) => {
    let now = moment(start);
    const end = moment(end);
    let dates = [];
    while (now.isSameOrBefore(end)) {
        dates.push(now.clone());
        now = now.add(1, 'days');
    }
    return dates;
}

CodePudding user response:

const dateList = ({ start, end }) => {
    let now = moment.utc(start);
    end = moment.utc(end);
    let dates = [];
    while (now.isValid() && end.isValid() && now.isSameOrBefore(end, 'day') /* end day inclusive */) {
        dates.push(now);
        now = moment(now).add(1, 'days'); // add 1 day on a new instance 
    }
    return dates;
}

console.log(dateList({start: '2026-05-12', end: '2026-05-14'}))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>



  • Related