获取今天的日期

使用 JavaScript Date 对象获取并格式化当前日期

问题

使用 JavaScript 输出今天的日期。

解答

基础方法

const today = new Date();

// 获取年月日
const year = today.getFullYear();      // 2024
const month = today.getMonth() + 1;    // 1-12(getMonth 返回 0-11)
const day = today.getDate();           // 1-31

console.log(`${year}-${month}-${day}`); // 2024-1-15

补零格式化

function formatDate(date) {
  const year = date.getFullYear();
  // padStart 补零,确保两位数
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  
  return `${year}-${month}-${day}`;
}

console.log(formatDate(new Date())); // 2024-01-15

使用 toLocaleDateString

const today = new Date();

// 默认格式
console.log(today.toLocaleDateString()); // 2024/1/15

// 指定格式
console.log(today.toLocaleDateString('zh-CN', {
  year: 'numeric',
  month: '2-digit',
  day: '2-digit'
})); // 2024/01/15

// ISO 格式(推荐用于数据传输)
console.log(today.toISOString().split('T')[0]); // 2024-01-15

使用 Intl.DateTimeFormat

const formatter = new Intl.DateTimeFormat('zh-CN', {
  year: 'numeric',
  month: '2-digit',
  day: '2-digit'
});

console.log(formatter.format(new Date())); // 2024/01/15

关键点

  • getMonth() 返回 0-11,需要 +1 才是实际月份
  • padStart(2, '0') 可以补零,保证两位数格式
  • toISOString() 返回 UTC 时间,适合数据存储和传输
  • toLocaleDateString() 支持本地化格式,适合展示
  • 生产环境推荐使用 day.js 或 date-fns 处理复杂日期操作