当我在 JavaScript 日期对象中将月份设置为 5 时,日期无效。 我知道月份是从零开始的。因此,第 5 个月表示 6 月。 但我得到的月份是七月。
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display the date after changing the month.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo1"></p>
<p id="demo"></p>
<script>
function myFunction() {
var d = new Date();
d.setYear(2017);
d.setMonth(5);
d.setDate(30);
document.getElementById("demo1").innerHTML = d.getMonth();
document.getElementById("demo").innerHTML = d;
}
</script>
</body>
</html>
Output:
6
Sun Jul 30 2017 15:11:20 GMT+0200 (W. Europe Daylight Time)
But, Ideally the output should be:
5
Sat Jun 30 2017 15:11:20 GMT+0200 (W. Europe Daylight Time)
最佳答案
这是发生了什么:
var d = new Date();
//d is today : which is 31st of May (day of your test)
d.setMonth(5)
//5 is June (setMonth starts at 0)
//As 31st of June doesn't exist, it is set as 1st of July.
d.setDate(30)
//d is now 30th of July
你最好使用完整的Date constructor :
new Date(year, month, date);
关于当月份设置为 5 时,Javascript 给出无效的月份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44285996/