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.

new Date() / 1000; // 1405792936.933

// Technically, .933 would be in milliseconds

Instead use:

Math.round(Date.now() / 1000); // 1405792937

// Or
Math.floor(Date.now() / 1000); // 1405792936

// Or
Math.ceil(Date.now() / 1000); // 1405792937

// Note: In general, I recommend `Math.round()`,
//   but there are use cases where
//   `Math.floor()` and `Math.ceil()`
//   might be better suited.

Also, values without floats are safer for conditional statements, because the granularity you obtain with floats may cause unwanted results. For example:

if (1405792936.993 < 1405792937) // true

Warning: Bitwise operators can cause issues when used to manipulate timestamps. For example, (new Date() / 1000) | 0 can also be used to "floor" the value into seconds, however that code 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 where needed.
  2. The signed 32 bit integer timestamp produced by the bitwise operator, causes the year 2038 problem as noted in the comments.