最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Getting a list of all dates within a given date range in JavaScript - Stack Overflow

programmeradmin0浏览0评论

I am trying to figure out if there are any helper functions available or any techniques that might be helpful to get a list of dates within a given date range.

Lets say the user enters the following parameters which would be a 2 year contract:
Day: 15
StartDate: 1/15/2015
EndDate: 12/15/2016

I would expect the date for each month within that period including the start and end months to be returned:

1/15/2015
2/15/2015
3/15/2015
.....
1/15/2016
2/15/2016
3/15/2016
.....
12/15/2016

I am trying to figure out if there are any helper functions available or any techniques that might be helpful to get a list of dates within a given date range.

Lets say the user enters the following parameters which would be a 2 year contract:
Day: 15
StartDate: 1/15/2015
EndDate: 12/15/2016

I would expect the date for each month within that period including the start and end months to be returned:

1/15/2015
2/15/2015
3/15/2015
.....
1/15/2016
2/15/2016
3/15/2016
.....
12/15/2016
Share Improve this question edited Feb 17, 2016 at 22:08 Transformer 3,7601 gold badge24 silver badges33 bronze badges asked Feb 17, 2016 at 21:35 Blake RivellBlake Rivell 13.9k33 gold badges128 silver badges259 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

You need to use setMonth and getMonth methods:

Note: As @RobG said in the ments, I made a mistake using a date format like this: 2015-12-01 for the example. The date format using - is not interpreted by all browsers. It is better use the / character instead.

Note 2: October 18th 2024: The above note is not true anymore. The documentation states that dates using slashes are non-standard (even if they are accepted and work in all browsers).

const start = new Date('2015-01-15');
const end = new Date('2016-12-15');

while (start <= end) {
    console.log( new Date(start) );
    start.setMonth( start.getMonth() + 1 );
}

A more dynamic solution:

function getDatesBtween(from, to, day) {

  const fromDate = new Date(from);
  const toDate = new Date(to);

  fromDate.setDate(day);
  toDate.setDate(day);

  const dates = [];

  while (fromDate <= toDate) {

    dates.push(new Date(fromDate));

    fromDate.setMonth(fromDate.getMonth() + 1);

  }

  return dates;

}

const dates = getDatesBtween('2015-01-15', '2016-12-15', 15);

console.log(dates);

Note: As @HBP has mentioned in the ments, the above solution does not take in account edge cases and it does not work with the last days of a month (29th, 30th and 31st days of the month). For example 2015/02/31 = 2015/03/03 in some cases and 2015/03/02 in others (in leap years). The next solution solves this problem:

function DateManager() {

  // Create a date with specific day
  function setDate(date, day) {

    date = new Date(date);
    date.setDate(day);
    date.setHours(23);

    return date;

  }

  // Generate dates method
  this.getDatesBetween = function(date1, date2, day) {

    const range1 = new Date(date1);
    const range2 = new Date(date2);
    const dates = [];
    let temp = null;
    
    date1 = setDate(date1, day);
    date2 = setDate(date2, day);

    while (date1 <= date2) {

      if (date1.getDate() != day) {

        temp = setDate(date1, 0);

        if (temp >= range1 && temp <= range2) dates.push(temp);

        date1 = setDate(date1, day);

      } else {

        temp = new Date(date1);

        if (temp >= range1 && temp <= range2) dates.push(temp);

        date1.setMonth(date1.getMonth() + 1);

      }

    }

    return dates;

  };

}

const manager = new DateManager();
const dates = manager.getDatesBetween('2015-01-15', '2016-12-15', 31);

console.log(dates);

The result will be something like:

2015/01/31
2015/02/28
2015/03/31
2015/04/30
2015/05/31
...
2016/02/29
...
2016/11/30

$("#from").datepicker();
$("#to").datepicker();


$('#getBetween').on('click', function () {
    var start = $("#from").datepicker("getDate"),
        end = $("#to").datepicker("getDate"),
        currentDate = new Date(start),
        between = []
    ;

    while (currentDate <= end) {
        between.push(new Date(currentDate));
        currentDate.setMonth(currentDate.getMonth() + 1);
    }
    
    $('#results').html(between.join('<br> '));
});
<link href="http://code.jquery./ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
      <script src="http://code.jquery./jquery-1.10.2.js"></script>
      <script src="http://code.jquery./ui/1.10.4/jquery-ui.js"></script>
<input id="from" />
<input id="to" />
<button id="getBetween">Get Between Dates</button>
<div id="results"></div>

I think getDate() + 1 should be able to solve the boundary condition.

var startDate = new Date("2020-02-01"); //YYYY-MM-DD
var endDate = new Date("2020-03-07"); //YYYY-MM-DD

var getDateArray = function(start, end) {
    var arr = new Array();
    var dt = new Date(start);
    while (dt <= end) {
        arr.push(new Date(dt));
        dt.setDate(dt.getDate() + 1);
    }
    return arr;
}

var dateArr = getDateArray(startDate, endDate);

// Output
document.write("Start Date: " + startDate + "<br>");
document.write("End Date: " + endDate + "<br>");
document.write("Date Array<br>")
for (var i = 0; i < dateArr.length; i++) {
    document.write(dateArr[i] + "<br>");
}
发布评论

评论列表(0)

  1. 暂无评论