以秒为单位获取当前date/时间

如何在JavaScript中获得当前date/时间?

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

….会给你自1970年1月1日午夜以来的秒数

参考

  Date.now() 

自纪元以来就会持续数毫秒。 不需要使用new

看看这里的参考: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now

(在IE8中不支持)

根据你的评论,我认为你正在寻找这样的东西:

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

然后在你的支票,你检查:

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

使用new Date().getTime() / 1000是获取秒的不完整解决scheme,因为它会生成浮点单位的时间戳。

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

更好的解决scheme是:

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

不带浮点数的值对条件语句也更安全,因为浮点数可能会产生不想要的结果。 用float获得的粒度可能比需要的多。

 if (1405792936.993 < 1405792937) // true 

从Javascript时代获得秒数的使用:

 date = new Date(); milliseconds = date.getTime(); seconds = milliseconds / 1000; 
 // 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> 

自1970年1月1日以来,最优雅的方式是以秒/毫秒为单位

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

让我build议更好的捷径:

 +new Date # Milliseconds since Linux epoch +new Date / 1000 # Seconds since Linux epoch Math.round(+new Date / 1000) #Seconds without decimals since Linux epoch 

这些JavaScript解决scheme为您提供1970年1月1日午夜以来的毫秒或秒。

IE 9+解决scheme(IE 8或更早版本不支持这一点):

 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. 

获取更多关于Date.now() : https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now

通用解决scheme:

 // '+' 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. 

小心使用,如果你不想要这种情况下的东西。

 if(1000000 < Math.round(1000000.2)) // false.