Skip to content

Instantly share code, notes, and snippets.

@codearachnid
Created November 19, 2013 19:04
Show Gist options
  • Save codearachnid/7550658 to your computer and use it in GitHub Desktop.
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
/**
* 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