Get current date/time in seconds

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

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

13条回答
  •  臣服心动
    2020-11-29 17:42

    Using new Date().getTime() / 1000 is an incomplete solution for obtaining the seconds, because it produces timestamps with floating-point units.

    const timestamp = new Date() / 1000; // 1405792936.933
    // Technically, .933 would be milliseconds. 
    

    A better solution would be:

    // Rounds the value
    const timestamp = Math.round(new Date() / 1000); // 1405792937
    
    // - OR -
    
    // Floors the value
    const timestamp = new Date() / 1000 | 0; // 1405792936
    

    Values without floats are also safer for conditional statements, as the float may produce unwanted results. The granularity you obtain with a float may be more than needed.

    if (1405792936.993 < 1405792937) // true
    

提交回复
热议问题