Skip to content

Instantly share code, notes, and snippets.

@benlesh
Created January 7, 2013 01:57
Show Gist options
  • Save benlesh/4471691 to your computer and use it in GitHub Desktop.
Save benlesh/4471691 to your computer and use it in GitHub Desktop.
Basic date add function in JavaScript.
/*
Copyright (c) 2013 Ben Lesh
[email protected]
MIT License
*/
;(function () {
var proto = Date.prototype;
function adder(value, getter, setter, toAdd) {
var d = new Date(value),
cv = getter.call(d);
setter.call(d, cv + toAdd);
return +d;
}
proto.addDays = function (days) {
return new Date(adder(this,
proto.getDate,
proto.setDate,
days));
};
proto.addHours = function (hours) {
return new Date(adder(this,
proto.getHours,
proto.setHours,
hours));
};
proto.addMinutes = function (minutes) {
return new Date(adder(this,
proto.getMinutes,
proto.setMinutes,
minutes));
};
proto.addSeconds = function (seconds) {
return new Date(adder(this,
proto.getSeconds,
proto.setSeconds,
seconds));
};
proto.addMilliseconds = function (ms) {
return new Date(adder(this,
proto.getMilliseconds,
proto.setMilliseconds,
ms));
};
proto.addYears = function (years) {
return new Date(adder(this,
proto.getFullYear,
proto.setFullYear,
years));
};
proto.addMonths = function (months) {
return new Date(adder(this,
proto.getMonth,
proto.setMonth,
months));
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment