JS Implementation Control Date Month increase or decrease

Source: Internet
Author: User

Define a current date variable

var mydate = new Date ();

Process Month Add function (date current date, num increment month "positive number: Add month, Negative: Decrease month")
function addmonth (date, num) {
    num = parseint (num);
    var sdate = datetodate (date);

    var syear = Sdate.getfullyear ();
    var smonth = sdate.getmonth () + 1;
    var sday = Sdate.getdate ();

    var eyear = syear;
    var emonth = smonth + num;
    var eday = sday;
    while (Emonth >) {
      eyear++;
      Emonth-= 12;
   }

    var eDate = new Date (eyear, eMonth-1, eday);

    while (Edate.getmonth ()! = eMonth-1) {
      eday--;
      eDate = new Date (eyear, eMonth-1, Eday);
   }

    return eDate;
};

function Datetodate (date) {
var sdate = new Date ();
if (typeof date = = ' object '
&& typeof New Date (). GetMonth = = "function"
) {
Sdate = date;
}
else if (typeof date = = "string") {
var arr = date.split ('-')
if (arr.length = = 3) {
Sdate = new Date (arr[0] + '-' + arr[1] + '-' + arr[2]);
}
}

return sdate;
};

Formatting date functions

Date.prototype.Format = function (FMT)
{//author:meizz
var o = {
"m+": This.getmonth () +1,//month
"D+": this.getdate (),//day
"H +": this.gethours (),//hour
"m+": this.getminutes (),//min
"S+": This.getseconds (),//sec
"q+": Math.floor ((This.getmonth () +3)/3),//Quarterly
"S": this.getmilliseconds ()//MS
};
if (/(y+)/.test (FMT))
Fmt=fmt.replace (Regexp.$1, (this.getfullyear () + ""). substr (4-regexp.$1.length));
For (var k in O)
if (New RegExp ("(" + K + ")"). Test (FMT))
FMT = Fmt.replace (regexp.$1, (regexp.$1.length==1)? (O[k]): (("XX" + o[k]). substr (("" + O[k]).));
return FMT;
};

Calling functions

var mydate = new Date ();
Alert (Addmonth (mydate, 1). Format ("Yyyy-mm-dd"));

Execution effect

JS Implementation Control Date Month increase or decrease

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.