Javascript - get array of dates between 2 dates

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

    This may help someone,

    You can get the row output from this and format the row_date object as you want.

    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

提交回复
热议问题