我如何获得当前日期或/和时间在秒使用Javascript?


当前回答

一种简单快速的方法,不需要创建日期对象并给出一个整数作为结果(如果发送小数,接受秒的api将会出错)

var nowincos = ~~(日期。 游戏机。log (nowInSeconds);

其他回答

 Date.now()

给出从epoch开始的毫秒数。不需要使用new。

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

(IE8不支持)

要从Javascript epoch中获取秒数,请使用:

date = new Date();
milliseconds = date.getTime();
seconds = milliseconds / 1000;

这些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.
var seconds = new Date().getTime() / 1000;

....能告诉你从1970年1月1日午夜开始的秒数吗

参考

我用这个:

Math.round(Date.now() / 1000)

不需要创建新对象(参见doc Date.now())