Javascript - get array of dates between 2 dates

后端 未结 25 1475
傲寒
傲寒 2020-11-22 15:16
var range = getDates(new Date(), new Date().addDays(7));

I\'d like \"range\" to be an array of date objects, one for each day between the two dates

25条回答
  •  误落风尘
    2020-11-22 15:48

    Here's a canned method that will accept Moment dates or strings or a mixture as inputs and generate an array of dates as Moment dates. If you don't want Moment dates as output then change what the map() method returns.

    const moment = require('moment');
    
    // ...
    
    /**
     * @param {string|import('moment').Moment} start
     * @param {string|import('moment').Moment} end
     * @returns {import('moment').Moment[]}
     */
    const getDateRange = (start, end) => {
      const s = moment.isMoment(start) ? start : moment(start);
      const e = moment.isMoment(end) ? end : moment(end);
      return [...Array(1 + e.diff(s, 'days')).keys()].map(n => moment(s).add(n, 'days'));
    };
    

提交回复
热议问题