美文网首页
五种javascript时间与时间戳之间的转换方式

五种javascript时间与时间戳之间的转换方式

作者: 我爱吃土豆a | 来源:发表于2019-11-23 11:24 被阅读0次

时间转时间戳:javascript获得时间戳的方法有五种,都是通过实例化时间对象 new Date() 来进一步获取当前的时间戳
第一种:不推荐这种办法,毫秒级别的数值被转化为000

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

结果:1477808630000

第二种:通过valueOf()函数返回指定对象的原始值获得准确的时间戳值

var timestamp2 = (new Date()).valueOf();
console.log(timestamp2);

结果:1477808630404

第三种:通过原型方法直接获得当前时间的毫秒值,准确

var timestamp3 = new Date().getTime();
console.log(timestamp3);

结果:1477808630404

第四种:将时间转化为一个number类型的数值,即时间戳

var timetamp4 = Number(new Date()) ;
console.log(timetamp4);

结果:1477808630404

第五种:ES5给Date提供了一种获取时间戳的新特性

var timetamp5 = Date.now();
console.log(timetamp5);

结果:1477808630404

相关文章

网友评论

      本文标题:五种javascript时间与时间戳之间的转换方式

      本文链接:https://www.haomeiwen.com/subject/hsfhwctx.html