Javascript - get array of dates between 2 dates

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

    I had trouble using the answers above. The date ranges were missing single days due to timezone shift caused by the local day light saving time (DST). I implemented a version using UTC dates that fixes that problem:

    function dateRange(startDate, endDate, steps = 1) {
      const dateArray = [];
      let currentDate = new Date(startDate);
    
      while (currentDate <= new Date(endDate)) {
        dateArray.push(new Date(currentDate));
        // Use UTC date to prevent problems with time zones and DST
        currentDate.setUTCDate(currentDate.getUTCDate() + steps);
      }
    
      return dateArray;
    }
    
    const dates = dateRange('2020-09-27', '2020-10-28');
    console.log(dates);

    Note: Whether a certain timezone or DST is applied, depends entirely on your locale. Overriding this is generally not a good idea. Using UTC dates mitigates most of the time related problems.

    Bonus: You can set the time interval for which you want to create timestamps with the optional steps parameter. If you want weekly timetamps set steps to 7.

提交回复
热议问题