Skip to content

Instantly share code, notes, and snippets.

@nim579
Created January 10, 2014 14:39
Show Gist options
  • Save nim579/8355167 to your computer and use it in GitHub Desktop.
Save nim579/8355167 to your computer and use it in GitHub Desktop.
Return week of month in Date class
Date.prototype.getWeekOfMonth = function(exact) {
var month = this.getMonth()
, year = this.getFullYear()
, firstWeekday = new Date(year, month, 1).getDay()
, lastDateOfMonth = new Date(year, month + 1, 0).getDate()
, offsetDate = this.getDate() + firstWeekday - 1
, index = 1 // start index at 0 or 1, your choice
, weeksInMonth = index + Math.ceil((lastDateOfMonth + firstWeekday - 7) / 7)
, week = index + Math.floor(offsetDate / 7)
;
if (exact || week < 2 + index) return week;
return week === weeksInMonth ? index + 5 : week;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment