在JavaScript中,获取当前时间的时间戳可以通过Date
对象来实现。时间戳通常指的是自1970年1月1日00:00:00 UTC到当前时间的毫秒数。
以下是获取当前时间戳的几种方法:
Date.now()
const timestamp = Date.now();
console.log(timestamp); // 输出当前时间的时间戳,例如:1633072800000
new Date().getTime()
const timestamp = new Date().getTime();
console.log(timestamp); // 输出当前时间的时间戳,例如:1633072800000
+new Date()
const timestamp = +new Date();
console.log(timestamp); // 输出当前时间的时间戳,例如:1633072800000
Date.parse(new Date())
const timestamp = Date.parse(new Date());
console.log(timestamp); // 输出当前时间的时间戳,例如:1633072800000
Date
对象的方法。Date
对象的方法。Date.now()
返回的是毫秒级的时间戳,如果需要更高精度的时间戳,可以使用performance.now()
,但需要注意的是,performance.now()
返回的是相对于页面加载的时间,不是绝对时间。Date.now()
返回的是毫秒级的时间戳,如果需要更高精度的时间戳,可以使用performance.now()
,但需要注意的是,performance.now()
返回的是相对于页面加载的时间,不是绝对时间。通过以上方法,你可以在JavaScript中获取当前时间的时间戳,并根据需要进行转换和使用。
领取专属 10元无门槛券
手把手带您无忧上云