当我们将日期转换为 JSON 时,为什么会发生这种情况? ?
var now = new Date();
// returns Wed Apr 29 2015 18:15:33 GMT+0100 (GMT Daylight Time)
var nowJSON = now.toJSON();
// returns "2015-04-29T17:15:33.863Z"
请注意,每个变量的小时都不同......
最佳答案
当 new Date()
打印到控制台时,您的操作系统定义打印的区域设置和格式。 Wed Apr 29 2015 18:15:33 GMT+0100(GMT 夏令时间)
是您的浏览器默认的时间。
当您打印 .toJSON
时,会发生这种情况:
http://es5.github.io/#x15.9.5.44
<小时/>This function provides a String representation of a Date object for use by JSON.stringify (15.12.3).
When the toJSON method is called with argument key, the following steps are taken:
- Let O be the result of calling ToObject, giving it the this value as its argument.
- Let tv be ToPrimitive(O, hint Number).
- If tv is a Number and is not finite, return null.
- Let toISO be the result of calling the [[Get]] internal method of O with argument "toISOString". 5.If IsCallable(toISO) is false, throw a TypeError exception.
- Return the result of calling the [[Call]] internal method of toISO with O as the this value and an empty argument list.
http://es5.github.io/#x15.9.5.43
<小时/>15.9.5.43 Date.prototype.toISOString ( )
This function returns a String value represent the instance in time represented by this Date object. The format of the String is the Date Time string format defined in 15.9.1.15. All fields are present in the String. The time zone is always UTC, denoted by the suffix Z. If the time value of this object is not a finite Number a RangeError exception is thrown.
http://es5.github.io/#x15.9.1.15
<小时/>15.9.1.15 Date Time String Format
ECMAScript defines a string interchange format for date-times based upon a simplification of the ISO 8601 Extended Format. The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ
原因是为了可以将日期序列化为字符串,然后将其带回对象,而不会丢失任何数据。
关于javascript - 不同的日期值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29950598/