javascript - 不同的日期值

标签 javascript datetime

当我们将日期转换为 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:

  1. Let O be the result of calling ToObject, giving it the this value as its argument.
  2. Let tv be ToPrimitive(O, hint Number).
  3. If tv is a Number and is not finite, return null.
  4. 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.
  5. 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/

相关文章:

javascript - $http.delete 回调在基本 CRUD 应用程序中未触发

javascript - 滚动包含来自不同域的页面的 iframe

javascript - 将参数从 Rally.data.ModelFactory.getModel 传递给调用方法

python - Matplotlib:季度小刻度标签

javascript - 将一个元素的颜色值链接到另一个元素

javascript - 在 Angular js 中强制单击

.NET DirectoryServices 查找方法使用 UTC 还是本地时间?

c# Lock with Thread.Sleep 不工作

java - 如何获得两次之间没有时区的差异?

php - sql中如何获取指定日期的数据