使用JavaScript获取当前时间戳的方法是使用Date.now()
函数或者new Date().getTime()
函数。这两个函数都可以返回自1970年1月1日 00:00:00 UTC到当前时间的毫秒数。其中,Date.now()
函数是ES5新增的函数,更加简洁方便。示例代码如下:
// 使用Date.now()函数获取当前时间戳
const timestamp1 = Date.now();
// 使用new Date().getTime()函数获取当前时间戳
const timestamp2 = new Date().getTime();
console.log(`当前时间戳1:${timestamp1}`); // 当前时间戳1:1631180172306
console.log(`当前时间戳2:${timestamp2}`); // 当前时间戳2:1631180172306
需要注意的是,获取的时间戳是基于UTC时间的,可能与本地时间存在差异。