var range = getDates(new Date(), new Date().addDays(7));

我想“范围”是一个日期对象的数组,一个为两个日期之间的每一天。

诀窍在于它还应该处理月份和年份的边界。


当前回答

我喜欢这样做

// hours * minutes * seconds * milliseconds
const DAY_IN_MS = 24 * 60 * 60 * 1000

/**
 * Get range of dates 
 * @param {Date} startDate 
 * @param {Number} numOfDays 
 * @returns {array}
 */
const dateRange = (startDate, numOfDays) => {
    const startDateMs = startDate.getTime()

    // get array of days and map it to Date object
    return [...Array(numOfDays).keys()].map(i => new Date(startDateMs + i * DAY_IN_MS))
}

其他回答

我看了上面所有的。最后我自己开始写作。你不需要花时间。原生的for循环就足够了,而且最有意义,因为for循环的存在是为了计算一个范围内的值。

一个衬套:

var getDaysArray = function(s,e) {for(var a=[],d=new Date(s);d<=new Date(e);d.setDate(d.getDate()+1)){ a.push(new Date(d));}return a;};

长版本

var getDaysArray = function(start, end) {
    for(var arr=[],dt=new Date(start); dt<=new Date(end); dt.setDate(dt.getDate()+1)){
        arr.push(new Date(dt));
    }
    return arr;
};

列出中间的日期:

var daylist = getDaysArray(new Date("2018-05-01"),new Date("2018-07-01"));
daylist.map((v)=>v.toISOString().slice(0,10)).join("")
/*
Output: 
    "2018-05-01
    2018-05-02
    2018-05-03
    ...
    2018-06-30
    2018-07-01"
*/

从过去日期到现在的日子:

var daylist = getDaysArray(new Date("2018-05-01"),new Date());
daylist.map((v)=>v.toISOString().slice(0,10)).join("")

这可能会帮助到一些人,

您可以从中获得行输出,并根据需要格式化row_date对象。

var from_date = '2016-01-01';
var to_date = '2016-02-20';

var dates = getDates(from_date, to_date);

console.log(dates);

function getDates(from_date, to_date) {
  var current_date = new Date(from_date);
  var end_date     = new Date(to_date);

  var getTimeDiff = Math.abs(current_date.getTime() - end_date.getTime());
  var date_range = Math.ceil(getTimeDiff / (1000 * 3600 * 24)) + 1 ;

  var weekday = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];
  var months = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
  var dates = new Array();

  for (var i = 0; i <= date_range; i++) {
     var getDate, getMonth = '';

     if(current_date.getDate() < 10) { getDate = ('0'+ current_date.getDate());}
     else{getDate = current_date.getDate();}

    if(current_date.getMonth() < 9) { getMonth = ('0'+ (current_date.getMonth()+1));}
    else{getMonth = current_date.getMonth();}

    var row_date = {day: getDate, month: getMonth, year: current_date.getFullYear()};
    var fmt_date = {weekDay: weekday[current_date.getDay()], date: getDate, month: months[current_date.getMonth()]};
    var is_weekend = false;
    if (current_date.getDay() == 0 || current_date.getDay() == 6) {
        is_weekend = true;
    }
    dates.push({row_date: row_date, fmt_date: fmt_date, is_weekend: is_weekend});
    current_date.setDate(current_date.getDate() + 1);
 }
 return dates;
}

https://gist.github.com/pranid/3c78f36253cbbc6a41a859c5d718f362.js

Generate an array of years: const DAYS = () => { const days = [] const dateStart = moment() const dateEnd = moment().add(30, ‘days') while (dateEnd.diff(dateStart, ‘days') >= 0) { days.push(dateStart.format(‘D')) dateStart.add(1, ‘days') } return days } console.log(DAYS()) Generate an arrays for month: const MONTHS = () => { const months = [] const dateStart = moment() const dateEnd = moment().add(12, ‘month') while (dateEnd.diff(dateStart, ‘months') >= 0) { months.push(dateStart.format(‘M')) dateStart.add(1, ‘month') } return months } console.log(MONTHS()) Generate an arrays for days: const DAYS = () => { const days = [] const dateStart = moment() const dateEnd = moment().add(30, ‘days') while (dateEnd.diff(dateStart, ‘days') >= 0) { days.push(dateStart.format(‘D')) dateStart.add(1, ‘days') } return days } console.log(DAYS())

如果你正在使用moment,那么你可以使用他们的“官方插件”来表示moment-range,然后这就变得微不足道了。

矩距节点示例:

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浏览器示例:

窗口(“moment-range”).extendMoment(时刻); 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(接触式(天))) < script src = " https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js " > < /脚本> < script src = " https://cdnjs.cloudflare.com/ajax/libs/moment-range/4.0.1/moment-range.js " > < /脚本>

日期FNS举例:

如果你使用date-fns,那么eachDay是你的朋友,你会得到迄今为止最短和最简洁的答案:

console.log (dateFns.eachDay ( 新日期(2018,11,30), 新日期(2019年30月09日) )) < script src = " https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.29.0/date_fns.min.js " > < /脚本>

我最近在用moment.js工作,下面做了一个戏法。

function getDateRange(startDate, endDate, dateFormat) {
        var dates = [],
            end = moment(endDate),
            diff = endDate.diff(startDate, 'days');

        if(!startDate.isValid() || !endDate.isValid() || diff <= 0) {
            return;
        }

        for(var i = 0; i < diff; i++) {
            dates.push(end.subtract(1,'d').format(dateFormat));
        }

        return dates;
    };
    console.log(getDateRange(startDate, endDate, dateFormat));

结果将是:

["09/03/2015", "10/03/2015", "11/03/2015", "12/03/2015", "13/03/2015", "14/03/2015", "15/03/2015", "16/03/2015", "17/03/2015", "18/03/2015"]