You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript获取「周二 22.11.2022」格式的今日及明日日期

获取带中文星期的指定日期格式

可以用JavaScript原生工具或手动拼接两种方式实现,既能生成「周二 22.11.2022」这类格式,还能自动处理补零、跨月/跨年的问题,比你当前的手动拼接更可靠。

方法一:用原生Intl.DateTimeFormat(推荐)

这个API支持本地化格式化,代码简洁且兼容性好:

// 封装格式化函数
function getFormattedDate(date) {
  // 获取中文星期简称(如「周二」)
  const weekday = new Intl.DateTimeFormat('zh-CN', { weekday: 'short' }).format(date);
  // 获取日.月.年格式,自动补零
  const dateStr = new Intl.DateTimeFormat('zh-CN', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric'
  }).format(date).replace(/\//g, '.');
  return `${weekday} ${dateStr}`;
}

// 获取今日和明日日期
const today = new Date();
const tomorrow = new Date(today);
tomorrow.setDate(today.getDate() + 1);

// 生成目标格式字符串
const todayFormatted = getFormattedDate(today);
const tomorrowFormatted = getFormattedDate(tomorrow);

console.log(todayFormatted); // 示例输出:周二 22.11.2022
console.log(tomorrowFormatted); // 示例输出:周三 23.11.2022

方法二:手动拼接(无需依赖原生API)

如果你需要更灵活的控制,也可以手动定义星期数组和补零逻辑:

// 中文星期数组,索引对应Date.getDay()的返回值(0=周日,1=周一...)
const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];

// 数字补零函数
function padZero(num) {
  return num.toString().padStart(2, '0');
}

// 格式化函数
function getFormattedDate(date) {
  const weekday = weekdays[date.getDay()];
  const day = padZero(date.getDate());
  const month = padZero(date.getMonth() + 1);
  const year = date.getFullYear();
  return `${weekday} ${day}.${month}.${year}`;
}

// 获取今日和明日
const today = new Date();
const tomorrow = new Date(today);
tomorrow.setDate(today.getDate() + 1);

console.log(getFormattedDate(today));
console.log(getFormattedDate(tomorrow));

注意点

  • 不要用day + 1直接计算明日日期,这种方式在当月最后一天会出错(比如1月31号,day+1=32,不符合实际日期),用setDate()方法能自动处理跨月、跨年。
  • 补零逻辑能保证日期格式统一,避免出现「2.3.2024」这类不规范的格式。

内容的提问来源于stack exchange,提问作者Muhammet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 08:40:44