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

如何在JavaScript中获取当前周的起止日期并解决跨月问题?

原生JavaScript实现周起止日期(解决跨月计算错误)

你遇到的跨月日期错误,本质是直接计算日期数值时未处理月份的自动进位/退位,改用原生JS的setDate()方法就能解决——这个方法会自动处理月份、年份的变化,不需要依赖Moment.js这类第三方库。

以下是两种常见周起始规则的实现:


规则1:周一为周第一天,周日为最后一天(匹配你给出的9月4日-9月10日示例)

function getCurrentWeekRange() {
  const today = new Date();
  const dayOfWeek = today.getDay(); // 0=周日,1-6=周一至周六

  // 计算本周一的日期
  const monday = new Date(today);
  const daysToMonday = dayOfWeek === 0 ? 6 : dayOfWeek - 1;
  monday.setDate(today.getDate() - daysToMonday);

  // 计算本周日的日期(周一加6天)
  const sunday = new Date(monday);
  sunday.setDate(monday.getDate() + 6);

  // 格式化日期为「X月X日」格式
  const formatDate = (date) => `${date.getMonth() + 1}月${date.getDate()}日`;

  return {
    start: formatDate(monday),
    end: formatDate(sunday)
  };
}

// 使用示例
const weekRange = getCurrentWeekRange();
console.log(`本周为${weekRange.start}至${weekRange.end}`);

规则2:周日为周第一天,周六为最后一天

如果你的业务场景以周日作为一周开始,用这个实现:

function getCurrentWeekRangeSunToSat() {
  const today = new Date();
  const dayOfWeek = today.getDay(); // 0=周日,1-6=周一至周六

  // 计算本周日的日期
  const sunday = new Date(today);
  sunday.setDate(today.getDate() - dayOfWeek);

  // 计算本周六的日期(周日加6天)
  const saturday = new Date(sunday);
  saturday.setDate(sunday.getDate() + 6);

  // 格式化日期
  const formatDate = (date) => `${date.getMonth() + 1}月${date.getDate()}日`;

  return {
    start: formatDate(sunday),
    end: formatDate(saturday)
  };
}

// 使用示例
const weekRange = getCurrentWeekRangeSunToSat();
console.log(`本周为${weekRange.start}至${weekRange.end}`);

核心原理

setDate()方法接收一个日期数值(1-31),当数值超出当前月份的最大天数时,会自动调整到下一个月;当数值小于1时,会自动调整到上一个月。比如8月31日调用setDate(34),会自动转为9月3日,完美解决跨月计算问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 21:15:36