// 将 JavaScript Date 对象转换为时间戳
// 创建一个新的 Date 对象,表示当前日期和时间
let currentDate = new Date();
// 方法 1: 使用 getTime() 方法获取时间戳(以毫秒为单位)
let timestampInMilliseconds = currentDate.getTime();
console.log("时间戳 (毫秒):", timestampInMilliseconds);
// 方法 2: 使用 valueOf() 方法获取时间戳(以毫秒为单位)
let timestampInMilliseconds2 = currentDate.valueOf();
console.log("时间戳 (毫秒):", timestampInMilliseconds2);
// 方法 3: 如果需要以秒为单位的时间戳,可以将毫秒除以 1000 并取整
let timestampInSeconds = Math.floor(currentDate.getTime() / 1000);
console.log("时间戳 (秒):", timestampInSeconds);
new Date():创建一个表示当前日期和时间的 Date 对象。getTime() 和 valueOf():这两个方法都可以返回自 1970 年 1 月 1 日 00:00:00 UTC 以来的毫秒数(即时间戳)。它们的功能是相同的。Math.floor(currentDate.getTime() / 1000):将毫秒数转换为秒数。因为 getTime() 返回的是毫秒,所以除以 1000 并使用 Math.floor() 取整,得到以秒为单位的时间戳。如果你只需要以秒为单位的时间戳,可以直接使用第三种方法。
上一篇:js 转换时间戳
下一篇:js 时间戳转时间
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站