如何获取所有周的起止日期及当前月份所有周的起止日期?
获取所有周及当前月份所有周的起止日期(基于Moment.js)
咱们先理清楚,你现有的代码确实只能拿到当前ISO标准下的一周起止日期(ISO周以周一为一周开始,周日为结束):
var startOfWeek = moment().startOf("isoWeek").toDate(); var endOfWeek = moment().endOf("isoWeek").toDate(); console.log(startOfWeek) console.log(endOfWeek)
接下来我分别解决你的两个需求:
一、获取某一年的所有周起止日期
通常我们说的“所有周”默认指一整年的所有周,这里可以写一个通用函数来生成指定年份的所有ISO周信息:
// 获取指定年份的所有ISO周起止日期 function getAllWeeksOfYear(year) { const weeks = []; // 定位到当年第一个ISO周的起始日 let currentWeek = moment(`${year}-01-01`).startOf("isoWeek"); // 循环遍历,直到进入下一年 while (currentWeek.year() === year) { const weekStart = currentWeek.clone().toDate(); const weekEnd = currentWeek.clone().endOf("isoWeek").toDate(); weeks.push({ weekNumber: currentWeek.isoWeek(), // 周数(ISO标准的周编号) start: weekStart, end: weekEnd }); // 切换到下一周 currentWeek.add(1, "week"); } return weeks; } // 示例:获取2024年的所有周 const allWeeks2024 = getAllWeeksOfYear(2024); console.log(allWeeks2024);
二、获取当前月份的所有周起止日期
这里要注意:月份的首尾周可能会跨月(比如当月1号在上个月的最后一周里,或者当月最后一天在下个月的第一周里)。下面的函数会把所有包含当月日期的周都列出来:
// 获取当前月份的所有周起止日期(包含跨月的周) function getAllWeeksOfCurrentMonth() { const weeks = []; const currentMonth = moment().month(); // 当前月份的索引(0-11) // 定位到当月第一天所在周的起始日 let currentWeek = moment().startOf("month").startOf("isoWeek"); // 循环遍历,直到周的起始日进入下一个月 while (currentWeek.month() === currentMonth) { const weekStart = currentWeek.clone().toDate(); const weekEnd = currentWeek.clone().endOf("isoWeek").toDate(); weeks.push({ weekNumber: currentWeek.isoWeek(), start: weekStart, end: weekEnd }); currentWeek.add(1, "week"); } // 👉 如果只需要**完全在当前月份内**的周,可以把上面的while条件改成: // while (currentWeek.endOf("isoWeek").month() === currentMonth) { ... } return weeks; } // 示例:获取当前月份的所有周 const currentMonthWeeks = getAllWeeksOfCurrentMonth(); console.log(currentMonthWeeks);
最后别忘了确保页面已经引入Moment.js脚本:
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.0/moment.min.js" integrity="sha512-Izh34nqeeR7/nwthfeE0SI3c8uhFSnqxV0sI9TvTcXiFJkMd6fB644O64BRq2P/LA/+7eRvCw4GmLsXksyTHBg==" crossorigin="anonymous"></script>
内容的提问来源于stack exchange,提问作者abhi
相关产品推荐
相关产品推荐

