当月份设置为 5 时,Javascript 给出无效的月份

标签 javascript

当我在 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/

相关文章:

javascript - 如何在按钮 onclick 操作的新弹出窗口中提交表单

javascript - JS : TypeError: this. _init 不是函数。 (在 'this._init()' 中, 'this._init' 未定义)

javascript - 无法使用manifoldjs创建包

javascript - 使用 JS 在 CSS 中删除作为背景图像的加载栏

javascript - Meteor 是否对模板名称强制使用 CamelCase?

javascript - 基于复选框添加数字

javascript - meteor 现场 Accordion 菜单

javascript - 为什么我的 javascript for 循环不工作?

javascript - 如何从 DOM 元素引用到 DOM 元素?

javascript - 检查 HTML 下拉选项