Get current date/time in seconds

Get current date/time in seconds

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

Solutions/Answers:

Solution 1:

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

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

Reference

Solution 2:

 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.)

Solution 3:

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

Solution 4:

Based on your comment, I think you’re looking for something like this:

var timeout = new Date().getTime() + 15*60*1000; //add 15 minutes;

Then in your check, you’re checking:

if(new Date().getTime() > timeout) {
  alert("Session has expired");
}

Solution 5:

To get the number of seconds from the Javascript epoch use:

date = new Date();
milliseconds = date.getTime();
seconds = milliseconds / 1000;

Solution 6:

// The Current Unix Timestamp
// 1443535752 seconds since Jan 01 1970. (UTC)

// Current time in seconds
console.log(Math.floor(new Date().valueOf() / 1000));  // 1443535752
console.log(Math.floor(Date.now() / 1000));            // 1443535752
console.log(Math.floor(new Date().getTime() / 1000));  // 1443535752
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

jQuery

console.log(Math.floor($.now() / 1000));               // 1443535752
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Related:  Set value to currency in