使用getDay Javascript获取明天的约会

时间:2012-02-14 04:22:51

标签: javascript variables date new-operator

我正在制作的是天气预报网站,我需要的是一周的日子(即“星期天”,“星期一”等)。为了得到明天的日期,我只是把“+ 1”放在另一个问题的建议中,但是当它到达星期六时,它会说“未定义”。如何在星期六到达时,我将如何实现,+ 1将循环到星期日?提前谢谢!

var day=new Date();
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";

document.getElementById('tomorrow').innerHTML = weekday[day.getDay() + 1];
document.getElementById('twodays').innerHTML = weekday[day.getDay() + 2];
document.getElementById('threedays').innerHTML = weekday[day.getDay() + 3];

2 个答案:

答案 0 :(得分:26)

要在javascript日期对象中添加一天,您可以执行以下操作:

var date =new Date();
//use the constructor to create by milliseconds
var tomorrow = new Date(date.getTime() + 24 * 60 * 60 * 1000);

注意,获取日期

Date.getDay根据一周中的哪一天返回0-6之间的数字。

所以你会这样做:

var date =new Date();
var tomorrow = new Date(date.getTime() + 24 * 60 * 60 * 1000);
var twoDays = new Date(date.getTime() + 2 * 24 * 60 * 60 * 1000);
var threeDays  = new Date(date.getTime() + 3 * 24 * 60 * 60 * 1000);

document.getElementById('tomorrow').innerHTML = weekday[tomorrow.getDay()];
document.getElementById('twodays').innerHTML = weekday[twoDays.getDay()];
document.getElementById('threedays').innerHTML = weekday[threeDays.getDay()];

编辑:修正拼写错误

答案 1 :(得分:9)

使用(day.getDay() + i) % 7。这只会在0-6之间返回结果。