JavaScript 获取本地时间与时间戳

在 JavaScript 中,可以使用 Date 对象获取本地时区的时间和时间戳。

获取本地时间:

const now = new Date();
const year = now.getFullYear();
const month = now.getMonth() + 1; // 月份从 0 开始,需要加 1
const day = now.getDate();
const hours = now.getHours();
const minutes = now.getMinutes();
const seconds = now.getSeconds();

// 格式化时间
const formattedTime = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;

console.log(formattedTime); // 输出格式化后的本地时间

获取时间戳:

const timestamp = Date.now(); // 获取当前时间的时间戳(毫秒)

console.log(timestamp); // 输出时间戳
html 文件大小:2.53KB