This should do it =)
function getWeeks(d) {
var first = new Date(d.getFullYear(),0,1);
var dayms = 1000 * 60 * 60 * 24;
var numday = ((d - first)/dayms)
var weeks = Math.ceil((numday + first.getDay()+1) / 7) ;
return weeks
}
console.log(getWeeks(new Date("31 Dec 2012"))) // 53
- This will first get the First Jan of the year you want to get the Weeks of
- Then substracts the first Jan from date given (results in the ms since that day)
- Divides it by 86400000 to get the number of day
- Adds the days since the sunday of the week from the first Jan
- Divides it all by 7
- Which should work regardless of Leap Years because it takes ms
If you want to stick to the Iso 8601 Week numbering which state for the first year in a week
- the week with the year's first Thursday in it (the formal ISO definition),
- the week with 4 January in it,
- the first week with the majority (four or more) of its days in the starting year, and
- the week starting with the Monday in the period 29 December – 4 January.
You can adjust it slightly to this
function getIsoWeeks(d) {
var first = new Date(d.getFullYear(),0,4);
var dayms = 1000 * 60 * 60 * 24;
var numday = ((d - first)/dayms)
var weeks = Math.ceil((numday + first.getDay()+1) / 7) ;
return weeks
}
console.log(getWeeks(new Date("31 Dec 2016"))) // 53
console.log(getIsoWeeks(new Date("31 Dec 2016")) //52
You could of course short the code and squeeze it all together, but for readability i declared the used vars like dayms
You can also take a look at this JSBin example