0

I need a JavaScript function that returns the number of days remaining from a particular date of every year.

I found the following code, but how can I make it repeatable for every year, instead of changing the year in the function manually?

function daysUntil(year, month, day) {
  var now = new Date(),
      dateEnd = new Date(year, month - 1, day), // months are zero-based
      days = (dateEnd - now) / 1000/60/60/24;   // convert milliseconds to days

  return Math.round(days);
}

daysUntil(2013, 10, 26);

I think my question above is not clear enough, i need to show days remaining in 26th October. So this starts again every year on 27th October. I don't need a loop for that.

4

1 回答 1

2

“我怎样才能使它每年都可重复,而不是手动更改功能年份?”

好吧,您不能从字面上每年都做无穷大,但是您可以轻松地添加一个循环来获得特定的年份范围:

var d;
for (var y = 2013; y < 2099; y++) {
    d = daysUntil(y, 10, 26);
    // do something with d, e.g.,
    console.log(d);
}

更新:您将此详细信息添加到您的问题中:

“我认为我上面的问题不够清楚,我需要显示 10 月 26 日的剩余天数。所以每年 10 月 27 日都会重新开始。我不需要循环。”

好的,这仍然不是很清楚,但我认为您是说您的输入只是日期和月份,并且您想要计算下一次该天/月滚动之前的天数,例如,离你下一个生日还有几天。如果是这样,也许是这样的:

function daysUntil(month, day) {
    var now = new Date(),
        currentYear = now.getFullYear(),
        dateEnd = new Date(currentYear, month - 1, day); // months are zero-based

    if (dateEnd - now < 0)  // have we already passed that date this year?
        dateEnd.setFullYear(currentYear + 1);

    return Math.ceil((dateEnd - now) / 1000/60/60/24);
}

console.log(daysUntil(10,11)); // 365           - results from today, Oct 11
console.log(daysUntil(10,26)); // 15
console.log(daysUntil(7,7));   // 269
于 2013-10-11T11:32:01.847 回答