领先的免费Web技术教程,涵盖HTML到ASP.NET

网站首页 > 知识剖析 正文

碎片时间学编程「335]:获取指定日期为一年中的第几周

nixiaole 2025-08-01 20:02:46 知识剖析 5 ℃


使用 Date 构造函数和
Date.prototype.getFullYear() 获取一年的第一天作为 Date 对象。 使用 Date.prototype.setDate()、Date.prototype.getDate() 和 Date.prototype.getDay() 以及取模 (%) 运算符来获取一年中的第一个星期一。 从给定日期中减去一年中的第一个星期一,然后除以一周中的毫秒数。 使用 Math.round() 获取一年中与给定日期对应的零索引周。 如果给定日期早于一年中的第一个星期一,则返回 -0。

const weekOfYear = date => {
  const startOfYear = new Date(date.getFullYear(), 0, 1);
  startOfYear.setDate(startOfYear.getDate() + (startOfYear.getDay() % 7));
  return Math.round((date - startOfYear) / (7 * 24 * 3600 * 1000));
};

示例:

weekOfYear(new Date('2021-06-18')); // 23

更多内容请访问我的网站:https://www.icoderoad.com

Tags:

最近发表
标签列表