在 JavaScript 中,可以使用 Date 对象来获取当前的时间戳,这是最常用的方法。 Date 对象的 getTime() 方法可以返回从 1970 年 1 月 1 日至今的毫秒数,即时间戳。
示例代码:
var timestamp = Date.now(); console.log(timestamp);
或者,也可以使用 Date 对象的 getTime() 方法来获取时间戳:
var timestamp = new Date().getTime(); console.log(timestamp);
也可以使用 Date.parse() 方法来获取时间戳:
var timestamp = Date.parse(new Date()); console.log(timestamp);
还可以使用 JavaScript 的 Math 对象的 floor() 方法来获取时间戳:
var timestamp = Math.floor(Date.now() / 1000); console.log(timestamp);
还可以使用 JavaScript 的 Date 对象的 getFullYear()、getMonth()、getDate()、getHours()、getMinutes()、getSeconds() 方法来获取时间戳:
var timestamp = Date.UTC( new Date().getFullYear(), new Date().getMonth(), new Date().getDate(), new Date().getHours(), new Date().getMinutes(), new Date().getSeconds() ); console.log(timestamp);
也可以使用 JavaScript 的 Date 对象的 valueOf() 方法来获取时间戳:
var timestamp = (new Date()).valueOf(); console.log(timestamp);
以上就是 JavaScript 中获取时间戳的几种方法,通过这些方法,可以方便快捷的获取当前时间戳,从而实现更多的功能。