javascript - javascript Date 对象的参数与文档不同?

标签 javascript date

我在 documentation 中读到它表示对于 Date 对象,月份参数是从零开始的。但不知何故,我的代码没有将月份返回为从零开始的..是因为我的计算机设置吗?会影响其他用户浏览我的网站吗?

我正在尝试获取上个月的 Date 对象。

我尝试过:

var mydate = new Date(2017, 11, 1); // result: Date 2017-11-30T17:00:00.000Z
var mydate = new Date(2017, 12, 1); // result: Date 2017-12-31T17:00:00.000Z
var mydate = new Date(2018, 0, 1); // result: Date 2017-12-31T17:00:00.000Z

最佳答案

来自参数注释部分的文档 -

Note: Where Date is called as a constructor with more than one argument, the specified arguments represent local time. If UTC is desired, use new Date(Date.UTC(...)) with the same arguments.

var mydate = new Date(Date.UTC(2017, 11, 1)); 
console.log(mydate);
var mydate = new Date(Date.UTC(2017, 12, 1)); 
console.log(mydate);
var mydate = new Date(Date.UTC(2018, 0, 1));
console.log(mydate);

P.S 为什么第二个输出是 2018-01-01 是因为

Note: Where Date is called as a constructor with more than one argument, if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. E.g. new Date(2013, 13, 1) is equivalent to new Date(2014, 1, 1), both create a date for 2014-02-01 (note that the month is 0-based). Similarly for other values: new Date(2013, 2, 1, 0, 70) is equivalent to new Date(2013, 2, 1, 1, 10) which both create a date for 2013-03-01T01:10:00.

关于javascript - javascript Date 对象的参数与文档不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48163127/

相关文章:

python - 在 Django View 中更改时间格式

java - 如何在 Java 中处理时间

javascript - 如何在 Javascript 中检查日期范围

javascript - 范围错误 : Maximum call stack size exceeded for Node. js

javascript - 将元素的文本 innerHTML 复制到剪贴板

javascript - 在 Visual Studio Code 中运行 JavaScript

php 日期到 mysql 返回 0

javascript - 通过 API 定位当前的 Google 设备位置?

php - 将表单发布到更多 URL

model-view-controller - JTemplates 使用 asp.net mvc 格式化日期