Created
November 19, 2013 19:04
-
-
Save codearachnid/7550658 to your computer and use it in GitHub Desktop.
A highly performant way to add days or date range (array) in JavaScript
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.addDays | |
* | |
*/ | |
Date.prototype.addDays = function( days ) { | |
var element = new Date( this.valueOf() ); | |
element.setDate( element.getDate() + days ); | |
return element; | |
} | |
/** | |
* Date.prototype.getDateRange | |
* | |
*/ | |
Date.prototype.getDateRange = function( start, end, interval ) { | |
interval = interval || 1; | |
var dateRange = [], start = new Date( start ), end = new Date( end ); | |
while ( start <= end ) { | |
dateRange.push( start ); | |
start = Date.prototype.addDays.call( start, interval ); | |
} | |
return dateRange; | |
} | |
/** | |
* DEMO | |
*/ | |
var dateArray = Date.prototype.getDateRange(new Date(), new Date().addDays(7)); | |
console.log(dateArray); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment