How can I get seconds since epoch in Javascript?

后端 未结 10 699
野的像风
野的像风 2020-12-13 23:48

On Unix, I can run date \'+%s\' to get the amount of seconds since epoch. But I need to query that in a browser front-end, not back-end.

Is there a way

相关标签:
10条回答
  • 2020-12-14 00:07

    My preferred way:

    var msEpoch = (+new Date());
    var sEpoch = (+new Date()) / 1000;
    

    For more information on the + jump down the rabbit hole.

    0 讨论(0)
  • 2020-12-14 00:13
    EPOCH means time from 01 January 1970
    var date = new Date();
    Following line will return the number of milliseconds from 01 Jaunary 1970
    var ms = date.getTime();
    Following line will convert milliseconds to seconds
    var seconds = Math.floor(ms/1000);
    console.log("Seconds since epoch =",seconds);
    
    0 讨论(0)
  • 2020-12-14 00:14

    You wanted seconds since epoch

    function seconds_since_epoch(){ return Math.floor( Date.now() / 1000 ) }
    

    example use

    foo = seconds_since_epoch();
    
    0 讨论(0)
  • 2020-12-14 00:16

    Try this:

    new Date().getTime() / 1000
    

    You might want to use Math.floor() or Math.round() to cut milliseconds fraction.

    0 讨论(0)
提交回复
热议问题