将Date递增到一个月中预定义的下一个日期

Incrementing a Date to the next occurence of a pre-defined day of the month

本文关键字:一个 预定义 日期 下一个 Date      更新时间:2023-09-26

我有一个应用程序,我要求用户在一个月的2天中选择一天。4号或18号。当用户选择了这个值,我就取这个值以及今天的日期。

在我做任何处理之前,我需要增加25天的管理工作。

day = parseInt(day);
var curDateTime = new Date().getTime(),
timeToAdd = (1000*60*60*24*25),
datePlusDays = new Date(),
finalDate = new Date();
datePlusDays.setTime(timeToAdd + curDateTime);
function incrementToSelected(toIncrement, incrementTo){
    var currentDay = parseInt(toIncrement.getDate());
    if (currentDay != incrementTo){
        var addedDay = new Date();
        addedDay.setTime(toIncrement.getTime() + (1000*60*60*24));
        incrementToSelected(addedDay, incrementTo );
    } else if (currentDay === incrementTo){
        finalDate = toIncrement;
    }
}
incrementToSelected(datePlusDays, day);

datePlusDays现在是今天的日期+ 25天。现在,我需要找到用户选择的下一个日期。

目前,我正在使用上面的方法添加一天(1000 * 60 * 60 * 24)到日期,并检查这是否是下一个发生,如果它不是添加另一个,如果它是设置finalDate与日期。

这确实有效,但在某些情况下,我得到一个最大调用堆栈大小超过错误。还有其他方法可以找到下一次出现的日期吗?

不需要乱搞时间戳。这是你想要的。它将日期设置为"incrementTo",并有条件地增加月份(如果incrementTo是<=当月的当前日期),并在必要时增加年份(如果月份是12月,则滚动到1月并增加年份)。

function incrementToSelected(toIncrement, incrementTo){
    if (toIncrement.getDate() >= incrementTo) {
        toIncrement.setDate(1); // Avoid month-rollover edge case
        var m = toIncrement.getMonth();
        if (m == 11) {
            toIncrement.setFullYear(toIncrement.getFullYear()+1);
            toIncrement.setMonth(0);
        } else {
            toIncrement.setMonth(m + 1);
        }
    }
    toIncrement.setDate(incrementTo);
}

使用Date函数自动滚动月份和年份更简单....

function Dday (admin, day) {
  var nextDate = new Date();
  nextDate.setDate (nextDate.getDate () + (admin || 25)); // add on the 25 days
  // Caution if day is not within range 1-31 this loop is infinite!
  while (nextDate.getDate () != (day || 4)) // keep adding 1 day till date == day.
    nextDate.setDate (nextDate.getDate () + 1);
  return nextDate;
}

我已经使该函数接受两个可选参数,admin是管理天数默认为25,day是一个月中的一天,默认为4。

我采纳了Steven的贡献,现在已经得到了下面的方法。

我在这个方法中去掉了函数的需要,我把它过于复杂化了,而实际上这是一个相当简单的技术。

day = parseInt(day);
var curDateTime = new Date().getTime(),
    timeToAdd = (1000*60*60*24*25),
    datePlusDays = new Date(timeToAdd + curDateTime);
if (day >= datePlusDays.getDate()){
    datePlusDays.setDate(day);
} else if (day < datePlusDays.getDate()){
    var m = datePlusDays.getMonth();
    if (m == 11){
        datePlusDays.setFullYear(datePlusDays.getFullYear() + 1);
        datePlusDays.setMonth(0);
    } else {
        datePlusDays.setMonth(datePlusDays.getMonth() + 1);
    }
    datePlusDays.setDate(day);
}
return datePlusDays;