How do you get a timestamp in JavaScript?

前端 未结 30 3079
情深已故
情深已故 2020-11-21 15:19

How can I get a timestamp in JavaScript?

Something similar to Unix timestamp, that is, a single number that represents the current time and date. Either as a number

30条回答
  •  无人共我
    2020-11-21 15:47

    Performance

    Today - 2020.04.23 I perform tests for chosen solutions. I tested on MacOs High Sierra 10.13.6 on Chrome 81.0, Safari 13.1, Firefox 75.0

    Conclusions

    • Solution Date.now() (E) is fastest on Chrome and Safari and second fast on Firefox and this is probably best choice for fast cross-browser solution
    • Solution performance.now() (G), what is surprising, is more than 100x faster than other solutions on Firefox but slowest on Chrome
    • Solutions C,D,F are quite slow on all browsers

    Details

    Results for chrome

    You can perform test on your machine HERE

    Code used in tests is presented in below snippet

    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() {
      // this solution returns time counted from loading the page.
      // (and on Chrome it gives better precission)
      return performance.now(); 
    }
    
    
    
    // TEST
    
    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);
    This snippet only presents code used in external benchmark

提交回复
热议问题