How can I get seconds since epoch in Javascript?

后端 未结 10 732
野的像风
野的像风 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:05

    The above solutions use instance properties. Another way is to use the class property Date.now:

    var time_in_millis = Date.now();
    var time_in_seconds = time_in_millis / 1000;
    

    If you want time_in_seconds to be an integer you have 2 options:

    a. If you want to be consistent with C style truncation:

    time_in_seconds_int = time_in_seconds >= 0 ?
                          Math.floor(time_in_seconds) : Math.ceil(time_in_seconds);
    

    b. If you want to just have the mathematical definition of integer division to hold, just take the floor. (Python's integer division does this).

    time_in_seconds_int = Math.floor(time_in_seconds);
    

提交回复
热议问题