关于JavaScript Date.now 与 Date.parse 的功能性质

image.png

相关代码
var time = new Date()

console.log(Date.now(time));
console.log(Date.parse(time));
console.log(time.getTime());
console.log((new Date(time)).getTime());
console.log(time.valueOf());
问题

Date.nowDate.parse 好似并不能准确的表达时间,这是为什么?

阅读 2.6k
3 个回答
  1. Date.now() 不带参数,所以 log 的是代码执行到那一行时的时间,和其他行不一致就很正常了
  2. Date.parse 期望得到一个 string 类型的参数,传递其他类型将强制 toString,而默认的 toString 方法不会包含毫秒信息。
var time = new Date();
time.toString = function(){console.log('time.toString called'); return Date.prototype.toString.apply(this);}
console.log(Date.parse(time))

// 修一下,toString 加上 milliseconds
time.toString = function(){return `${this.getFullYear()}-${this.getMonth()+1}-${this.getDate()} ${this.getHours()}:${this.getMinutes()}:${this.getSeconds()}.${this.getMilliseconds()}`};
console.log(time.valueOf() === Date.parse(time))

Date.parse(),只能精确到秒,后面的三位毫秒数都是000。
Date.now(), 能精确到毫秒。你的第二段输出我试了一下,第一次Date.now()跟其他的一样,第二次就不一样了。
我感觉是因为执行时间的问题。这段代码执行了好多次,每次结果都不一样。

image.png

最关键的是Date对象信息是以毫秒(ms)为单位的,而一般Date.parse()需要分析的时间仅仅是会精确到秒(s)的,如果Date.parse('04 Dec 1995 00:12:00.1 GMT')是在有些浏览器(firefox)会出错,另外的如(chrome)则不出错。

var time = new Date()
console.log(Date.parse(time));

中time对象实例的值在被Date.parse()处理时实质是以类似Thu Dec 10 2020 09:05:09的字符串传入的,本身就忽略了毫秒时间部分,而被Date()来实例化一个对象时是直接以time.getTime()值传入的。
另外Date.now()是没有参数的。
此外其实不建议用Date.parse(),因为在不同的浏览器中结果可能是不同的。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题