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