Obtener la fecha/hora actual en segundos


¿Cómo obtengo la fecha/hora actual en segundos en Javascript?

Author: Jonathan Allard, 2010-09-30

10 answers

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

....le dará los segundos desde la medianoche, 1 ene 1970

Referencia

 371
Author: sje397,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-06 09:28:25
 Date.now()

Da milisegundos desde la época. No es necesario utilizar new.

Echa un vistazo a la referencia aquí: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now

(No soportado en IE8.)

 90
Author: Konstantin Schubert,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-09 20:01:58

Usar new Date().getTime() / 1000 es una solución incompleta para obtener los segundos, porque produce marcas de tiempo con unidades de punto flotante.

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

Una mejor solución sería:

var timestamp = new Date() / 1000 | 0; // 1405792936
// Floors the value

// - OR -

var timestamp = Math.round(new Date() / 1000); // 1405792937
// Rounds the value

Los valores sin flotadores también son más seguros para las sentencias condicionales, ya que el flotador puede producir resultados no deseados. La granularidad que se obtiene con un flotador puede ser más de lo necesario.

if (1405792936.993 < 1405792937) // true
 42
Author: tfmontague,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-07 22:57:11

Basado en tu comentario, creo que estás buscando algo como esto:

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

Entonces en su cheque, usted está comprobando:

if(new Date().getTime() > timeout) {
  alert("Session has expired");
}
 37
Author: Nick Craver,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-30 12:08:28

Para obtener el número de segundos del Javascript epoch use:

date = new Date();
milliseconds = date.getTime();
seconds = milliseconds / 1000;
 14
Author: Lazarus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-30 11:57:12

// 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>
 6
Author: blueberry0xff,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-15 17:57:51

Estas soluciones JavaScript le dan los milisegundos o los segundos desde la medianoche del 1 de enero de 1970.

La solución IE 9+ (IE 8 o la versión anterior no admite esto.):

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.

Para obtener más información sobre Date.now(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now

La solución genérica:

// ‘+’ 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.

Tenga cuidado de usar, si usted no quiere algo como este caso.

if(1000000 < Math.round(1000000.2)) // false.
 1
Author: K._,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-22 14:19:24

Puedes conocer otra forma de obtener tiempo en segundos/milisegundos desde el 1 de enero de 1970:

var milliseconds = +new Date;        
var seconds = milliseconds / 1000;

Pero tenga cuidado con tal enfoque, porque podría ser difícil de leer y entender.

 1
Author: tetta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-14 06:24:42

Mejores atajos:

+new Date # Milliseconds since Linux epoch
+new Date / 1000 # Seconds since Linux epoch
Math.round(+new Date / 1000) #Seconds without decimals since Linux epoch
 1
Author: dr.dimitru,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-09 12:13:58
Date.now()-Math.floor(Date.now()/1000/60/60/24)*24*60*60*1000

Esto debería darte los milisegundos desde el comienzo del día.

(Date.now()-Math.floor(Date.now()/1000/60/60/24)*24*60*60*1000)/1000

Esto debería darte segundos.

 0
Author: CEO RecDecLec,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-19 01:26:21