我是一名尝试通过 Lynda.com 上的视频类(class)学习 JavaScript 的新手
讲师从 alert()
代码开始,使我们编写的内容显示在警告框中。然后他展示了如何编写代码以在警告框中返回今天的日期:
var date = new Date();
alert("Today's date is " + date);
I am including this to show that the date variable was set for the current date.
下一步是让我们写的内容出现在打开文档顶部的实际网页部分。
document.body.innerHTML = "<h1>The date today is " + date + "<h1>"
它以相同的日期返回,仅 6 月 15 日
,这次是在网页本身。
下一部分是我得到不同月份的地方,尽管我输入的正是我应该输入的内容。为了使其更具可读性,我们被告知可以获取特定信息的 get 函数。
document.body.innerHTML = "<h1>The date today is " + date.getMonth() + "/" + date.getDate() + "/" + date.getFullYear() + "</h1>"
它返回:
The date today is 5/15/2018
我不明白为什么它告诉我现在是 2018 年 5 月 15 日,而更早的日期是正确的。我不知道我的代码哪里错了。如能提供任何帮助,我们将不胜感激。
最佳答案
这是因为返回的月份是从零开始的,所以 6 月确实是第 5 个月。
来自 MDN 上的 date.getMonth()
文档:
The getMonth() method returns the month in the specified date according to local time, as a zero-based value (where zero indicates the first month of the year)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMonth
关于javascript - 得到两个不同的日期月份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50885190/