Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
47
rated 0 times [  54] [ 7]  / answers: 1 / hits: 21696  / 11 Years ago, wed, august 28, 2013, 12:00:00

Moment js has a function to get the number of days in a month : http://momentjs.com/docs/#/displaying/days-in-month/



However I could not find a function to find the number of iso weeks in a year (52 or 53).


More From » momentjs

 Answers
10

Here's an answer that isn't dependent on a library. It uses a function to calculate the week in the year that 31 December falls in for the required year. If the week is 1 (i.e. 31 December is in the first week of the following year), it moves the day number lower until it gets a different value, which will be the last week of the required year.





function getWeekNumber(d) {
// Copy date so don't modify original
d = new Date(+d);
d.setHours(0, 0, 0, 0);
// Set to nearest Thursday: current date + 4 - current day number
// Make Sunday's day number 7
d.setDate(d.getDate() + 4 - (d.getDay() || 7));
// Get first day of year
var yearStart = new Date(d.getFullYear(), 0, 1);
// Calculate full weeks to nearest Thursday
var weekNo = Math.ceil((((d - yearStart) / 86400000) + 1) / 7)
// Return array of year and week number
return [d.getFullYear(), weekNo];
}

function weeksInYear(year) {
var month = 11,
day = 31,
week;

// Find week that 31 Dec is in. If is first week, reduce date until
// get previous week.
do {
d = new Date(year, month, day--);
week = getWeekNumber(d)[1];
} while (week == 1);

return week;
}

[2015, 2016, 2029, new Date().getFullYear()].forEach(year =>
console.log(`${year} has ${weeksInYear(year)} weeks`)
);





The getWeekNumber code is from here: Get week of year in JavaScript like in PHP.



Edit



Alternatively, if 31 December is in week 1 of the following year, then the subject year has 52 weeks and otherwise has 53 weeks.





function getWeekNumber(d) {
d = new Date(+d);
d.setHours(0, 0, 0, 0);
d.setDate(d.getDate() + 4 - (d.getDay() || 7));
var yearStart = new Date(d.getFullYear(), 0, 1);
var weekNo = Math.ceil((((d - yearStart) / 86400000) + 1) / 7)
return [d.getFullYear(), weekNo];
}

function weeksInYear(year) {
var d = new Date(year, 11, 31);
var week = getWeekNumber(d)[1];
return week == 1 ? 52 : week;
}

[2015, 2016, 2029, new Date().getFullYear()].forEach(year =>
console.log(`${year} has ${weeksInYear(year)} weeks`)
);




[#76085] Monday, August 26, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
joannam

Total Points: 331
Total Questions: 106
Total Answers: 105

Location: Sweden
Member since Mon, May 8, 2023
1 Year ago
;