Javascript - get array of dates between 2 dates

后端 未结 25 1463
傲寒
傲寒 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:51

    If you are using moment then you can use their "official plugin" for ranges moment-range and then this becomes trivial.

    moment-range node example:

    const Moment = require('moment');
    const MomentRange = require('moment-range');
    const moment = MomentRange.extendMoment(Moment);
    
    const start = new Date("11/30/2018"), end = new Date("09/30/2019")
    const range = moment.range(moment(start), moment(end));
    
    console.log(Array.from(range.by('day')))
    

    moment-range browser example:

    window['moment-range'].extendMoment(moment);
    
    const start = new Date("11/30/2018"), end = new Date("09/30/2019")
    const range = moment.range(moment(start), moment(end));
    
    console.log(Array.from(range.by('day')))
    
    

    date fns example:

    If you are using date-fns then eachDay is your friend and you get by far the shortest and most concise answer:

    console.log(dateFns.eachDay(
      new Date(2018, 11, 30),
      new Date(2019, 30, 09)
    ))

提交回复
热议问题