如何根据指定日期计算对应的日历周?
I struggled for a while finding a simple yet accurate solution when searching for "Calculating the Week for a given Date"—most either didn't handle edge cases properly or were overly complex. Here's the implementation I came up with that follows ISO week rules (Monday as the first day of the week, Week 1 containing January 4th of the year):
The Implementation
getWeekOfDay: function(d){ var date1 = new Date(d.getFullYear(), d.getMonth(), d.getDate()); var yearWeek; var firstMondayOfWeek1 = this.getMondayOfWeekOneOfAGivenYear(date1.getFullYear()); var weekNumber = Math.ceil((((date1 - firstMondayOfWeek1) / 86400000) + 1) / 7); yearWeek = date1.getFullYear() + "." + weekNumber; // Handle dates that fall in the last week of the previous year (e.g., Jan 1, 2012) if(weekNumber <= 0 ){ firstMondayOfWeek1 = this.getMondayOfWeekOneOfAGivenYear(date1.getFullYear() - 1); weekNumber = Math.ceil((((date1 - firstMondayOfWeek1) / 86400000) + 1) / 7); yearWeek = (date1.getFullYear() - 1) + "." + weekNumber; } // Handle years where Week 53 rolls over to next year (e.g., Dec 29, 2014; Dec 28, 2020) if(weekNumber === 53 ){ var Dec31 = new Date(date1.getFullYear(), 11, 31); if(Dec31.getDay() < 4){ yearWeek = (date1.getFullYear() + 1) + "." + 1; } } return yearWeek; }, getMondayOfWeekOneOfAGivenYear: function(year){ // ISO rule: January 4th always falls in Week 1 of the year var fourthJan = new Date(year, 0, 4); var day = fourthJan.getDay(); // Treat Sunday as day 7 (since ISO weeks start on Monday) if (day === 0) { day = 7; } var firstMondayOfW1 = new Date(fourthJan); firstMondayOfW1.setDate(firstMondayOfW1.getDate() + (1 - day)); return firstMondayOfW1; },
Key Logic Breakdown
getMondayOfWeekOneOfAGivenYear: The foundation of this implementation relies on the ISO standard rule that January 4th is always in Week 1 of the year. We calculate the first Monday of Week 1 by adjusting from January 4th—if January 4th is a Sunday, we treat it as day 7 to correctly shift back to the preceding Monday.getWeekOfDay:- Create a copy of the input date to avoid modifying the original object.
- Calculate the week number by finding the day difference between the input date and the first Monday of Week 1, then converting that to weeks.
- Edge case 1: If the calculated week number is ≤0, the date belongs to the last week of the previous year—we recalculate using the prior year's Week 1 Monday.
- Edge case 2: If the week number is 53, we check if December 31st of the current year is a Wednesday or earlier (since such years don't have a full Week 53, so those days belong to Week 1 of the next year).
内容的提问来源于stack exchange,提问作者Arvind

