JavaScript中获取时间戳的方法 技术背景 在JavaScript开发中,时间戳是一个常见的需求,它可以用于记录事件发生的时间、计算时间间隔等。JavaScript中的时间戳通常是指从Unix纪元(1970年1月1日 00:00:00 UTC)开始到指定时间的毫秒数或秒数。不同的场景可能需要不同精度的时间戳,因此掌握获取时间戳的多种方法非常重要。
实现步骤 获取毫秒级时间戳 使用Date.now()
方法: 使用一元运算符+
调用Date.prototype.valueOf
: 直接调用valueOf
方法: 直接调用getTime
方法: 为了支持IE8及更早版本,创建Date.now
的垫片: 1 2 3 if (!Date .now ) { Date .now = function ( ) { return new Date ().getTime (); } }
获取秒级时间戳 使用Math.floor
方法: 1 Math .floor (Date .now () / 1000 );
使用按位或运算符(性能稍快但可读性差且未来可能有问题): 获取更高分辨率的毫秒级时间戳 使用performance.now
方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 var isPerformanceSupported = ( window .performance && window .performance .now && window .performance .timing && window .performance .timing .navigationStart );var timeStampInMs = ( isPerformanceSupported ? window .performance .now () + window .performance .timing .navigationStart : Date .now () );console .log (timeStampInMs, Date .now ());
核心代码 测试不同方法的性能 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 function A ( ) { return new Date ().getTime (); }function B ( ) { return new Date ().valueOf (); }function C ( ) { return +new Date (); }function D ( ) { return new Date ()*1 ; }function E ( ) { return Date .now (); }function F ( ) { return Number (new Date ()); }function G ( ) { return performance.now (); } log = (n,f ) => console .log (`${n} : ${f()} ` );log ('A' ,A);log ('B' ,B);log ('C' ,C);log ('D' ,D);log ('E' ,E);log ('F' ,F);log ('G' ,G);
生成特定格式的时间戳字符串 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 function displayTime ( ) { var str = "" ; var currentTime = new Date (); var hours = currentTime.getHours (); var minutes = currentTime.getMinutes (); var seconds = currentTime.getSeconds (); if (minutes < 10 ) { minutes = "0" + minutes; } if (seconds < 10 ) { seconds = "0" + seconds; } str += hours + ":" + minutes + ":" + seconds + " " ; if (hours > 11 ){ str += "PM" ; } else { str += "AM" ; } return str; }
使用moment.js获取时间戳 1 2 3 4 5 6 moment ().valueOf ();moment ().unix ();moment ('2015-07-12 14:59:23' , 'YYYY-MM-DD HH:mm:ss' ).valueOf ();
最佳实践 兼容性 :如果需要兼容旧版本浏览器(如IE8及更早版本),使用new Date().getTime()
或为Date.now
创建垫片。性能 :在Chrome和Safari中,Date.now()
是最快的跨浏览器解决方案;在Firefox中,performance.now()
速度极快,但在Chrome中较慢。精度 :如果需要更高的精度,使用performance.now()
。第三方库 :如果需要处理复杂的时间操作,推荐使用moment.js
。常见问题 按位或运算符的问题 :Date.now() / 1000 | 0
可能在2038年出现问题,因为它会将64位双精度数转换为32位整数,导致信息丢失。建议使用Math.floor
代替。客户端时间不准确 :JavaScript中的时间戳依赖于客户端计算机的设置,因此可能不准确。为了获得更准确的时间戳,建议从服务器端获取。