使用getDay获取明天的日期JavaScript

pbwdgjma  于 2023-09-29  发布在  Java
关注(0)|答案(3)|浏览(150)

我正在做的是一个天气预报网站,我需要的是一周中的几天(即。“星期日”、“星期一”等)。为了得到明天的日期,我只是把“+ 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];
yjghlzjz

yjghlzjz1#

要在JavaScript Date对象中添加一天,您可以执行以下操作:

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

注意,获取Date
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()];

编辑:修复错字

5kgi1eie

5kgi1eie2#

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

lvjbypge

lvjbypge3#

我只是想让他的答案更清晰些。在这种情况下,i是整数,因此接下来的两天看起来像:

document.getElementById('twodays').innerHTML = weekday[(day.getDay() + 2) % 7];

在我的版本中,我还将数组清理为以下内容:

const weekday = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];

相关问题