Last active
December 2, 2024 08:51
-
-
Save jean-lourenco/729c70b9b512778dbdf9 to your computer and use it in GitHub Desktop.
Javascript - Date isSameWeek() function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
The javascript function isSameWeek() checks if two dates are in the same week. | |
The extra logic in the code validades when the week begins in a year and ends in another one. | |
The getWeek() function is found at http://javascript.about.com/library/blweekyear.htm | |
------ | |
A [Pen](http://codepen.io/jeanlourenco/pen/gpabqr) by [Jean Carlos Lourenço](http://codepen.io/jeanlourenco) on [CodePen](http://codepen.io/). | |
[License](http://codepen.io/jeanlourenco/pen/gpabqr/license). |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Date.prototype.resetTime = function(){ | |
this.setHours(0, 0, 0, 0); | |
return this; | |
} | |
Date.prototype.getWeek = function(){ | |
var date = this.resetTime(); | |
var onejan = new Date(date.getFullYear(), 0, 1); | |
return Math.ceil((((date - onejan) / 86400000) + onejan.getDay() + 1) / 7); | |
} | |
Date.prototype.isLastWeekOfTheYear = function(){ | |
return this.getWeek() == 53; | |
} | |
Date.prototype.isFirstWeekOfTheYear = function(){ | |
return this.getWeek() == 1; | |
} | |
Date.prototype.isSameWeek = function(dateToCompare){ | |
var sameWeek = this.getWeek() == dateToCompare.getWeek() && this.getFullYear() == dateToCompare.getFullYear(); | |
if (!sameWeek && this.isLastWeekOfTheYear() && dateToCompare.isFirstWeekOfTheYear()){ | |
sameWeek = this.getDay() < dateToCompare.getDay(); | |
} | |
return sameWeek; | |
} | |
var date1 = new Date(2012, 11, 30); | |
var date2 = new Date(2013, 0, 5); | |
console.log('Same week? ' + date1.isSameWeek(date2)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment