跳转到内容

JavaScript 获取与格式化时间 ​

在 JavaScript 中,获取当前时间可以使用 Date 对象。以下是一些常见的方法来获取和格式化当前时间。

警告

获取到的都是设备时间而非实际时间!

获取当前日期和时间 ​

javascript
const now = new Date();
console.log(now); // 输出当前的日期和时间

获取当前年份、月份、日期、小时、分钟、秒 ​

javascript
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();

console.log(`当前时间:${year}-${month}-${day} ${hours}:${minutes}:${seconds}`);

注意

获取日期用的是getDate();而不是getDay();。

格式化时间 ​

如果需要更灵活的时间格式,可以使用 toLocaleString 方法:

javascript
const now = new Date();
const formattedDate = now.toLocaleString(); // 根据用户的区域设置格式化
console.log(formattedDate);

自定义格式化 ​

如果需要自定义时间格式,可以使用字符串拼接:

javascript
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');  // 确保月份为两位数
const day = String(now.getDate()).padStart(2, '0');  // 确保日期为两位数
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
const seconds = String(now.getSeconds()).padStart(2, '0');

const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
console.log(formattedDate);