Skip to content

Instantly share code, notes, and snippets.

@sriharshav
Created October 17, 2012 11:02
Show Gist options
  • Select an option

  • Save sriharshav/3904970 to your computer and use it in GitHub Desktop.

Select an option

Save sriharshav/3904970 to your computer and use it in GitHub Desktop.
Javascript date time helpers
//##Gets x days Ago##
Date.prototype.daysAgo = function (days) {
if (isNaN(days) || (days ==0)) {
return;
}
this.setDate(this.getDate() - days);
}
//##Gets x weeks Ago##
Date.prototype.weeksAgo = function (weeks) {
if (isNaN(weeks) || (weeks ==0)) {
return;
}
this.setDate(this.getDate() - (weeks*7));
}
//##Gets x months Ago##
Date.prototype.monthsAgo = function (months) {
if (isNaN(months) || (months ==0)) {
return;
}
var month = this.getMonth();
this.setMonth(month - months);
while(this.getMonth() == month) {
this.daysAgo(1);
}
}
//##Gets day count in year##
Date.prototype.getDayOfYear = function () {
var year = this.getFullYear();
var month = this.getMonth()+1;
var days = this.getDate();
for (var i = 1; i < month; i+=1) {
days+=new Date(year, i, 0).getDate();
}
return days;
}
//##Gets week count in year##
Date.prototype.getWeekOfYear = function () {
var days = this.getDayOfYear();
//Sunday is 0, Monday is 1, and so on.
var firstDay = new Date(this.getFullYear(), 0, 1).getDay();
var offset = 7 - firstDay;
var week = 0;
if (days <= offset) {
week = 1;
} else {
week = parseInt((days - 1 - offset) / 7) + 2
}
return week;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment