繁体   English   中英

计算JavaScript中某个日期范围之间的重复日期

[英]Calculate the recurring dates between a range of dates in javascript

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

   //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]);

                }

该代码既可以像您一样在自己的逻辑中实现,也可以使用库。 我为以后的功能重用了后来的库。

这是否符合您的期望? 对于间隔中的天数,将需要一个明确的参数:

// 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上的示例。

该函数为两个日期之间的每个[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;
}

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

  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");

这种方法可以让您进行必要的工作,例如排除周末和节假日。

您可以使用简单的比较(例如d1 <= d2 is_same_day_or_before(d1,d2)来实现is_same_day_or_before(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);
}

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

    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));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM