How to enumerate dates between two dates in Moment

后端 未结 7 1513
太阳男子
太阳男子 2020-12-13 03:58

I have two moment dates:

var fromDate = moment(new Date(\'1/1/2014\'));
var toDate   = moment(new Date(\'6/1/2014\'));

Does moment provide

7条回答
  •  北海茫月
    2020-12-13 04:20

    As an extension of Kyle's answer - I've been trying to get this to work with Unix timestamps and after lots of trial and error I got it to work and thought I'd post it here in case anyone is seeking the same thing and needs it. See my code below:

    fromDate = moment.unix(req.params.dateFrom).format('YYYY-MM-DD')
    toDate = moment.unix(req.params.dateTo).format('YYYY-MM-DD')
    
    // Returns an array of dates between the two dates
    function enumerateDaysBetweenDates(startDate, endDate) {
        startDate = moment(startDate);
        endDate = moment(endDate);
    
        var now = startDate, dates = [];
    
        while (now.isBefore(endDate) || now.isSame(endDate)) {
            dates.push(now.format('YYYY-MM-DD'));
            now.add(1, 'days');
        }
        return dates;
    };
    

    Note that I convert it to Unix, then convert that value to moment again. This was the issue that I had, you need to make it a moment value again in order for this to work.

    Example usage:

    fromDate = '2017/03/11' // AFTER conversion from Unix
    toDate = '2017/03/13' // AFTER conversion from Unix
    
    console.log(enumerateDaysBetweenDates(fromDate, toDate));
    

    Will return:

    ['2017/03/11', '2017/03/12', '2017/03/13']
    

提交回复
热议问题