Get current date/time in seconds Get current date/time in seconds javascript javascript

Get current date/time in seconds


var seconds = new Date().getTime() / 1000;

....will give you the seconds since midnight, 1 Jan 1970

Reference


 Date.now()

gives milliseconds since epoch. No need to use new.

Check out the reference here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now

(Not supported in IE8.)


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:

const timestamp = Math.round(new Date() / 1000); // 1405792937

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

Warning: Using bitwise operators to manipulate timestamps can cause problems. For example, new Date() / 1000 | 0 will also "floor" the number, however it causes the following issues:

  1. By default Javascript numbers are type 64 bit (double precision) floats, and bitwise operators implicitly convert that type into signed 32 bit integers. Arguably, the type should not be implicitly converted by the compiler, and instead the developer should make the conversion when needed.
  2. The signed 32 bit integer timestamp produced causes the year 2038 problem as noted in the comments.