我如何获得当前日期或/和时间在秒使用Javascript?
当前回答
var seconds = new Date().getTime() / 1000;
....能告诉你从1970年1月1日午夜开始的秒数吗
参考
其他回答
Date.now()
给出从epoch开始的毫秒数。不需要使用new。
在这里查看参考资料:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now
(IE8不支持)
这些JavaScript解决方案提供了从1970年1月1日午夜开始的毫秒或秒。
IE 9+解决方案(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
通用解决方案:
// ‘+’ 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.
使用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对象,因为Date.now()是一个静态方法,这意味着可以直接从API对象的构造函数访问它。
你可以这样做
const ms = Date.now() const sec = Math.round(ms/1000) 文档。写(“秒:${交会}”)
一些有趣的事情
自1970年1月1日00:00:00 UTC开始的秒数实时更新
const element = document.getElementById('root') setInterval(() => { let seconds = Math.round(Date.now()/1000) 元素。innerHTML = seconds },1000) 从1970年1月1日00:00:00 UTC开始的秒数 < h1 id =“根”> < / h1 >
要获得今天的总秒数:
getTodaysTotalSeconds(){
let date = new Date();
return +(date.getHours() * 60 * 60) + (date.getMinutes() * 60) + date.getSeconds();
}
我在return中使用了add +它在int中返回。这可能对其他开发人员有所帮助。:)