zoukankan      html  css  js  c++  java
  • [转]js add month 加n月

    本文转自:http://stackoverflow.com/questions/5645058/how-to-add-months-to-a-date-in-javascript/5645126

    I took a look at the datejs and stripped out the code necessary to add months to a date handling edge cases (leap year, shorter months, etc):

    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 () { 
        return Date.isLeapYear(this.getFullYear()); 
    };
    
    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;
    };

    This will add "addMonths()" function to any javascript date object that should handle edge cases. Thanks to Coolite Inc!

    Use:

    var myDate = new Date("01/31/2012");
    var result1 = myDate.addMonths(1);
    
    var myDate2 = new Date("01/31/2011");
    var result2 = myDate2.addMonths(1);
    

    ->> newDate.addMonths -> mydate.addMonths

    result1 = "Feb 29 2012"

    result2 = "Feb 28 2011"

     

  • 相关阅读:
    docker基础
    paas平台
    django 多数据分库
    s3对象存储
    css
    __construct()和__initialize()
    js function
    phpstorm ftp 使用
    php
    thinkphp 笔记
  • 原文地址:https://www.cnblogs.com/freeliver54/p/4287958.html
Copyright © 2011-2022 走看看