我怎样才能在Javascript中获得自纪元以来的秒数? [英] How can I get seconds since epoch in Javascript?
本文介绍了我怎样才能在Javascript中获得自纪元以来的秒数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Unix上,我可以运行 date'+%s'
来获取自纪元以来的秒数。但我需要在浏览器前端查询,而不是后端。
On Unix, I can run date '+%s'
to get the amount of seconds since epoch. But I need to query that in a browser front-end, not back-end.
有没有办法在JavaScript中查找自Epoch以来的秒数?
Is there a way to find out seconds since Epoch in JavaScript?
推荐答案
var seconds = new Date() / 1000;
或者,对于一个不那么黑的版本:
Or, for a less hacky version:
var d = new Date();
var seconds = d.getTime() / 1000;
别忘了 Math.floor()
或 Math.round()
要舍入到最接近的整数,否则你可能得到一个你不想要的奇数小数:
Don't forget to Math.floor()
or Math.round()
to round to nearest whole number or you might get a very odd decimal that you don't want:
var d = new Date();
var seconds = Math.round(d.getTime() / 1000);
这篇关于我怎样才能在Javascript中获得自纪元以来的秒数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文