0

我需要能够使用 javascript 每周五自动更改日期。每个星期五,日期将更改为下一个星期五。

例如,日期当前将显示“10 月 25 日星期五”,在 10 月 25 日星期五的特定时间,我需要将日期更改为“11 月 1 日星期五”等等。

因此,每周在特定时间我将其设置为自动更新到下周五。

4

2 回答 2

1
var txtFriday = $("#friday"), // a HTML id
    myDate = new Date();

// The getDay() method returns the day of the week (from 0 to 6) for the specified date.
// Note: Sunday is 0, Monday is 1, and so on.
if (myDate.getDay() === 5){
    //Note: If adding five days to a date shifts the month or year, the changes are handled automatically by the Date object itself!
    myDate.setDate(myDate.getDate()+7);
}

txtFriday.text(myDate);
于 2013-10-21T09:19:58.260 回答
0

一般的想法是,在页面加载时,您运行一个 setTimeout,它应该在您更改显示日期的特定时间到期(并为下周五设置另一个 setTimeout)。

有一些关于精度的注意事项(您可能希望执行一个明显早于所需日期到期的 setTimeout 并运行较小长度的超时,直到您获得实际日期)。

示例代码:

function getNextFriday() {
    var today = new Date();
    var nextFriday = new Date(today.getFullYear(), today.getMonth(), today.getDate()-today.getDay()+7+5);
  // TODO: change to the apropriate time
    return nextFriday;
}

window.setTimeout(changeMyDate, getNextFriday()-new Date());

function changeMyDate() {
  console.log('Time to change the date');
  window.setTimeout(changeMyDate, getNextFriday() - new Date());
}
于 2013-10-21T09:19:50.500 回答