input type="week" 返回 ISO 周格式字符串如"2024-W23",需用 JavaScript 解析年份和周数,再依 ISO 8601 规则(周一为每周首日,第1周含当年首个周四)计算当周周一与周日日期,最终返回形如{start:"2024-06-03",end:"2024-06-09"}的对象。

input type="week" 本身只返回形如 "2024-W23" 的字符串(ISO 周格式),不直接提供起止日期。需用 JavaScript 解析该字符串,再根据 ISO 8601 规则(周一为每周第一天,第1周是包含当年第一个周四的那周)计算出当周周一和周日的具体日期。
解析 week 字符串获取年份和周数
从 input.value(如 "2024-W23")中提取年份和周数:
- 用
.split('-W')拆分,注意兼容浏览器可能返回空值,建议加校验 - 年份转为数字,周数也转为数字(注意:周数可能带前导零,
parseInt可自动处理) - 示例:
const [year, week] = input.value.split('-W').map(Number);
根据年份和周数推算当周周一(ISO 标准)
ISO 周的周一需满足两个条件:属于该 ISO 年,且是该周第1天。可靠方法是:
- 先构造该年1月4日(因它必定在第1周内),再算出该日是星期几(
getDay(),注意:JS 中周日=0,需转为 ISO 周一=1) - 用公式:
firstMonOfISOYear = new Date(year, 0, 4 - (new Date(year, 0, 4).getDay() + 6) % 7) - 然后加上
(week - 1) * 7天,得到当周周一
快速生成周一和周日日期对象
得到周一日期后,周日就是周一加6天:
- 周一:
const monday = new Date(firstMonOfISOYear); monday.setDate(firstMonOfISOYear.getDate() + (week - 1) * 7); - 周日:
const sunday = new Date(monday); sunday.setDate(monday.getDate() + 6); - 输出格式建议用
toISOString().slice(0,10)得到"YYYY-MM-DD"字符串
完整可复用函数示例
封装成函数,支持输入 "2024-W23",返回 { start: "2024-06-03", end: "2024-06-09" }:
function weekToDateRange(weekStr) {
if (!/^\d{4}-W\d{2}$/.test(weekStr)) return null;
const [y, w] = weekStr.split('-W').map(Number);
const jan4 = new Date(y, 0, 4);
const dayOfWeek = (jan4.getDay() + 6) % 7; // 转为 ISO:周一=0
const firstMon = new Date(y, 0, 4 - dayOfWeek);
const monday = new Date(firstMon);
monday.setDate(firstMon.getDate() + (w - 1) * 7);
const sunday = new Date(monday);
sunday.setDate(monday.getDate() + 6);
return {
start: monday.toISOString().slice(0, 10),
end: sunday.toISOString().slice(0, 10)
};
}
// 使用:
// const range = weekToDateRange("2024-W23"); // → {start:"2024-06-03", end:"2024-06-09"}











