在javascript中计算一系列日期之间的重复日期

Calculate the recurring dates between a range of dates in javascript

本文关键字:日期 之间 一系列 javascript 计算      更新时间:2023-09-26

重复如何实际工作不是问题。我想实现一种方法来计算具有指定重复间隔的两个日期之间的天数。这可能是每周、每月、每两个月(我不完全知道)每年等。到目前为止,我做的最简单的事情是以下内容,它让我计算两个日期之间的所有天数,然后以七天的间隔循环它们,每周重复一次。如果您能建议我更好和正确的实施方式,我将不胜感激。谢谢。

   //Push in the selected dates in the selected array.
                for (var i = 1; i < between.length; i += 7) {
                    selected.push(between[i]);
                    console.log(between[i]);
                }

此函数为两个日期之间的每个 [interval] 和 [intervalType](例如每 1 个月)提供一个日期。如有必要,它还可以更正周末的日期。这就是你的想法吗?

这里有一个jsFiddle演示。

function recurringDates(startDate, endDate, interval, intervalType, noweekends) {
    intervalType = intervalType || 'Date';
    var date = startDate;
    var recurrent = [];
    var setget = {set: 'set'+intervalType, get: 'get'+intervalType};
    while (date < endDate) {
      recurrent.push( noweekends ? noWeekend() : new Date(date) );
      date[setget.set](date[setget.get]()+interval);
    }
    
    // add 1 day for sunday, subtract one for saturday
    function noWeekend() {
        var add, currdate = new Date(date), day = date.getDay();
        if (~[6,0].indexOf(day)) {
          currdate.setDate(currdate.getDate() + (add = day == 6 ? -1 : 1));
        }
        return new Date(currdate);
    }
    return recurrent;
}

这是否与您期望的一样?它需要对间隔中的天数进行显式参数:

// startDate: Date()
// endDate: Date()
// interval: Number() number of days between recurring dates
function recurringDates(startDate, endDate, interval) {
  // initialize date variable with start date
  var date = startDate;
  // create array to hold result dates
  var dates = [];
  // check for dates in range
  while ((date = addDays(date, interval)) < endDate) {
    // add new date to array
    dates.push(date);
  }
  // return result dates
  return dates;
}
function addDays(date, days) {
  var newDate = new Date(date);
  newDate.setDate(date.getDate() + days);
  return newDate;
}
var startDate = new Date(2015, 0, 1);
var endDate = new Date(2016, 0, 1);
var interval = 20;
console.log(recurringDates(startDate, endDate, interval));

下面是 JSFiddle 上的示例。

如果您只需要重复次数,则最快的(无论日期范围的大小如何,恒定时间)是执行以下操作。

  1. 计算日期范围内的天数。请参阅下面的公式。

  2. 确定该天数内可以容纳多少重复周期。这可以通过简单的划分和地板操作来完成。例如,如果日期范围有 100 天,并且您希望每周重复,则重复次数为Math.floor(100 / 7)

如果您将日期

范围的开始日期设置为第一次重复的日期,这将有所帮助。

如果要获取实际日期,并且还想执行诸如排除周末或节假日之类的操作,则需要按如下方式迭代日期范围。

// psuedo-code
d = start_date;
interval_days = recurrence_days;
n = 0;
while(is_same_day_or_before(d, end_date)) {
  if(not_an_excluded_day(d)) {
    print(d);
    n++;
  }
  d = add_days(d, interval_days)
}
print("There are " + n + " recurrences");

如有必要,此方法将允许您执行诸如排除周末和节假日之类的操作。

您可以通过简单的比较来实现is_same_day_or_before(d1,d2),例如 d1 <= d2 .如果d1d2可以位于不同的时区,那么您需要更复杂的检查来适应夏令时调整等。

add_days功能更直接。

function add_days(d,n) {
  var d = new Date(d.getTime());
  d.setDate(d.getDate() + n);
  return d;
}

计算两个(javascript)日期之间的日期数

无论日期范围有多大,此处的答案和下面复制的答案以供参考,都为您提供了一种快速准确的方法来执行此操作。

var _MS_PER_DAY = 1000 * 60 * 60 * 24;
// a and b are javascript Date objects
function dateDiffInDays(a, b) {
  // Discard the time and time-zone information.
  var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
  var utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
  return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}

代码可以像以前一样在您自己的逻辑中实现,也可以使用库。我稍后重用了该库.js以实现定期功能。

您可以先以毫秒为单位计算差异,然后以其他差异格式显示毫秒差异,如下所示:

    Date.daysBetween = function( date1, date2 ) {
  //Get 1 day in milliseconds
  var one_day=1000*60*60*24;
  // Convert both dates to milliseconds
  var date1_ms = date1.getTime();
  var date2_ms = date2.getTime();
  // Calculate the difference in milliseconds
  var difference_ms = date2_ms - date1_ms;
  //take out milliseconds
  difference_ms = difference_ms/1000;
  var seconds = Math.floor(difference_ms % 60);
  difference_ms = difference_ms/60; 
  var minutes = Math.floor(difference_ms % 60);
  difference_ms = difference_ms/60; 
  var hours = Math.floor(difference_ms % 24);  
  var days = Math.floor(difference_ms/24);
  return days + ' days, ' + hours + ' hours, ' + minutes + ' minutes, and ' + seconds + ' seconds';
}
//Set the two dates
var y2k  = new Date(2000, 0, 1);
var Jan1st2010 = new Date(y2k.getYear() + 10, y2k.getMonth(), y2k.getDate());
var today= new Date();
//displays "Days from Wed Jan 01 0110 00:00:00 GMT-0500 (Eastern Standard Time) to Tue Dec 27 2011 12:14:02 GMT-0500 (Eastern Standard Time): 694686 days, 12 hours, 14 minutes, and 2 seconds"
console.log('Days from ' + Jan1st2010 + ' to ' + today + ': ' + Date.daysBetween(Jan1st2010, today));