将 JavaScript Date 对象转换为 JSON 字符串时,日期更改为前一天

Vig*_* VS 3 javascript jquery json date object

我想将 Date 对象(日期为 MM/DD/YYYY 格式的“12/01/2019”)作为 JSON 字符串传递给 API。但是,当将此日期(不考虑时区)转换为 JSON 字符串时,日期会更改为前一天。请参阅下面给出的代码:

var newDate = new Date("12/01/19");
console.log(newDate)        // Showing Sun Dec 01 2019 00:00:00 GMT+0530 (India Standard Time)
var jsonDate = JSON.stringify(newDate);
console.log(jsonDate)       // Showing "2019-11-30T18:30:00.000Z"
Run Code Online (Sandbox Code Playgroud)

日期 2019 年 12 月 1 日更改为 2019 年 11 月 30 日。就我而言,我无法考虑时间或时区。我也无法使用“Moment JS”。

为什么会出现这种情况?谁能具体说明这个奇怪问题背后的原因吗?

Nic*_*ick 6

由于您的日期字符串采用非标准格式,因此Date构造函数将其视为本地时间(请参阅手册Date.parse()中的“假定时区差异”部分)。然而,JSON.stringify()调用Date.toJSON()which总是输出UTC偏移量为零的Date.toISOString()时间。因此,您需要通过减去时区偏移量将日期转换为 UTC,该时区偏移量可以通过 获得。Date.getTimezoneOffset()

或者,提供 ISO 格式 ( YYYY-MM-DD) 日期字符串,无需调整,因为Date构造函数会将其视为 UTC 时间。

// non-standard date format
var newDate = new Date('12/01/19');
console.log(newDate.toJSON());

var os = newDate.getTimezoneOffset();
newDate = new Date(newDate.getTime() - os * 60 * 1000);
console.log(newDate.toJSON());

// ISO format date
var newDate2 = new Date('2019-12-01');
console.log(newDate2.toJSON());
Run Code Online (Sandbox Code Playgroud)