Get current date/time in seconds

前端 未结 13 1658
失恋的感觉
失恋的感觉 2020-11-29 17:14

How do I get the current date/time in seconds in Javascript?

13条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-29 17:36

    These JavaScript solutions give you the milliseconds or the seconds since the midnight, January 1st, 1970.

    The IE 9+ solution(IE 8 or the older version doesn't support this.):

    var timestampInMilliseconds = Date.now();
    var timestampInSeconds = Date.now() / 1000; // A float value; not an integer.
        timestampInSeconds = Math.floor(Date.now() / 1000); // Floor it to get the seconds.
        timestampInSeconds = Date.now() / 1000 | 0; // Also you can do floor it like this.
        timestampInSeconds = Math.round(Date.now() / 1000); // Round it to get the seconds.
    

    To get more information about Date.now(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now

    The generic solution:

    // ‘+’ operator makes the operand numeric.
    // And ‘new’ operator can be used without the arguments ‘(……)’.
    var timestampInMilliseconds = +new Date;
    var timestampInSeconds = +new Date / 1000; // A float value; not an intger.
        timestampInSeconds = Math.floor(+new Date / 1000); // Floor it to get the seconds.
        timestampInSeconds = +new Date / 1000 | 0; // Also you can do floor it like this.
        timestampInSeconds = Math.round(+new Date / 1000); // Round it to get the seconds.
    

    Be careful to use, if you don't want something like this case.

    if(1000000 < Math.round(1000000.2)) // false.
    

提交回复
热议问题