我需要能够自动更改日期每周五使用javascript。每周五,日期将改为下周五。
例如,日期当前为‘星期五10月25日’,在10月25日星期五的特定时间,我需要将日期更改为‘星期五11月1日’,依此类推。
因此,我每周都会在特定的时间自动将其更新到下周五。
发布于 2013-10-21 17:19:58
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-21 17:19:51
一般的想法是,在页面加载时,您运行一个setTimeout,该setTimeout将在您指定的时间过期,从而更改显示的日期(并为下个星期五设置另一个for )。
在处理精度方面有一些注意事项(您可能希望创建一个比预期日期早得多的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());
}https://stackoverflow.com/questions/19489674
复制相似问题