javascript - 得到两个不同的日期月份

标签 javascript html datetime

我是一名尝试通过 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/

相关文章:

javascript - 该 Controller 功能有任何问题吗?

javascript - 一个数字可以有多少种不同的解码方式

javascript - 在 javascript 中将日期转换为 JSON 时出现问题

python - 字符串中的日期时间不匹配

c++ - 序列化和反序列化 time_t 变量后结果不正确

javascript - 在 d3 树布局中查找链接终点的坐标

javascript - 如何使用 javascript 在 Phonegap 的推特上发布图片

javascript - 使用 AJAX 为 AJAX 预加载图像

javascript - CKEditor 在服务器上返回错误的图像路径

html - 如果doctype是html as HTML5,那么IE6是哪种模式?