Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

关于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 好似并不能准确的表达时间,这是为什么?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...