Tuesday, November 4, 2014

JavaScript: add months to a date handling edge cases (leap year, shorter months, etc)

Slip from dateJS:
Date.isLeapYear = function (year) {
       return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0));
};

Date.getDaysInMonth = function (year, month) {
    return [31, (Date.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
};

Date.prototype.isLeapYear = function () {
    var y = this.getFullYear();
    return (((y % 4 === 0) && (y % 100 !== 0)) || (y % 400 === 0));
};

Date.prototype.getDaysInMonth = function () {
    return Date.getDaysInMonth(this.getFullYear(), this.getMonth());
};

Date.prototype.addMonths = function (value) {
   var n = this.getDate();
   this.setDate(1);
   this.setMonth(this.getMonth() + value);
   this.setDate(Math.min(n, this.getDaysInMonth()));
   return this;
};

Or using moment.js:
moment().add('months',1).format('YYYY-MM-DD');
moment().add('months',1).calendar();
moment().subtract('days', 1).calendar();
moment("20111031", "YYYYMMDD").fromNow(); // x years ago
moment("20120620", "YYYYMMDD").fromNow(); // x years ago
moment().startOf('day').fromNow();        // x hours ago
moment().endOf('day').fromNow();          // in xx hours
moment().startOf('hour').fromNow();     // xx minutes ago

No comments:

Post a Comment