我如何获得当前日期或/和时间在秒使用Javascript?
当前回答
使用new Date(). gettime() / 1000是获取秒的不完整解决方案,因为它会生成带有浮点单位的时间戳。
new Date() / 1000; // 1405792936.933
// Technically, .933 would be in milliseconds
而不是使用:
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.
此外,对于条件语句来说,没有浮动的值更安全,因为使用浮动获得的粒度可能会导致不想要的结果。例如:
if (1405792936.993 < 1405792937) // true
警告:位操作符用于操作时间戳时会导致问题。例如,(new Date() / 1000) | 0也可以用来将值“下压”为秒,但该代码会导致以下问题:
默认情况下,Javascript数字类型是64位(双精度)浮点数,位操作符隐式地将该类型转换为32位有符号整数。可以说,类型不应该由编译器隐式转换,而应该由开发人员在需要的地方进行转换。 按位运算符产生的有符号32位整型时间戳会导致注释中提到的2038年问题。
其他回答
Date.now()-Math.floor(Date.now()/1000/60/60/24)*24*60*60*1000
这应该会给出从一天开始算起的毫秒数。
(Date.now()-Math.floor(Date.now()/1000/60/60/24)*24*60*60*1000)/1000
这应该会给你一些时间。
(Date.now()-(Date.now()/1000/60/60/24|0)*24*60*60*1000)/1000
与前面相同,只是使用了位运算符来计算天数的下限。
要从Javascript epoch中获取秒数,请使用:
date = new Date();
milliseconds = date.getTime();
seconds = milliseconds / 1000;
更好的捷径:
+new Date # Milliseconds since Linux epoch
+new Date / 1000 # Seconds since Linux epoch
Math.round(+new Date / 1000) #Seconds without decimals since Linux epoch
如果你只是在THREE JS中需要几秒钟,使用下面的代码中的一个在函数uses window.requestAnimationFrame()
let sec = parseInt(Date.now().toString()[10]);console.log('计数秒=> '+秒);
或 let currentTime= Date.now();
let secAsString= time.toString()[10];
let sec = parseInt(t);
console.log('计数秒=>'+秒);
var seconds = new Date().getTime() / 1000;
....能告诉你从1970年1月1日午夜开始的秒数吗
参考