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

JavaScript如何从YYYY-WW格式的年周数字符串创建Date对象

问题解答

原生JavaScript没有内置的简便方法可以直接解析YYYY-WW格式的年周字符串生成Date对象,因为ECMAScript标准里没有定义对周数格式的解析规则,不同浏览器的实现逻辑也不统一,直接传入new Date('2020-44')会得到无效日期。

你可以通过以下两种方式实现转换:

方案1:原生JS手动实现

核心逻辑遵循通用的ISO 8601周规则(周一为一周起始,每年第一个周至少包含4天在当年,即当年1月4日一定属于第一个周),自己计算日期偏移即可:

function getDateFromYearWeek(yearWeekStr) {
  // 拆分获取年份和周数
  const [year, week] = yearWeekStr.split('-').map(Number);
  // 以当年1月4日为基准定位第一个周
  const firstWeekBase = new Date(year, 0, 4);
  // 调整周计数:ISO规则周一为1,周日为7
  const dayOfWeek = firstWeekBase.getDay() || 7;
  // 计算当年第一个周的周一日期
  const firstWeekMonday = new Date(firstWeekBase);
  firstWeekMonday.setDate(firstWeekBase.getDate() - (dayOfWeek - 1));
  // 叠加周数偏移,得到目标周的周一日期
  const targetDate = new Date(firstWeekMonday);
  targetDate.setDate(firstWeekMonday.getDate() + (week - 1) * 7);
  return targetDate;
}

// 测试:2020年第44周的周一为2020-10-26
console.log(getDateFromYearWeek('2020-44'));

注意:如果你的业务规则里周起始为周日,或者周判定逻辑不同,对应修改偏移计算规则即可。

方案2:用第三方日期库快速实现

如果项目已经引入了成熟的日期处理库,可以直接调用封装好的解析方法,不用自己处理边界兼容:

  • dayjs(配合isoWeek插件):
import dayjs from 'dayjs';
import isoWeek from 'dayjs/plugin/isoWeek';
dayjs.extend(isoWeek);

const targetDate = dayjs('2020-44', 'YYYY-WW').toDate();
  • moment.js:
const targetDate = moment('2020-44', 'YYYY-WW').toDate();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 09:24:00