每周五更改日期

时间:2013-10-21 08:37:58

标签: javascript jquery date

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

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

所以每周我都会在特定的时间将其设置为自动更新到下周五。

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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());
}
相关问题