Javascript tips for adding or subtracting dates by month

Source: Internet
Author: User
JavaScript code example for date addition and subtraction. Because JavaScript does not have the AddDays method similar to C #, you need to write a function to implement date addition and subtraction. I will share it with you here. if you have any friends, you can refer to the projects you need and write one for yourself. Javascript date plus or minus by month

  
   Script 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;} function addMonth (date, num) {num = parseInt (num); var sDate = dateToDate (date); var s Year = sDate. getFullYear (); var sMonth = sDate. getMonth () + 1; var sDay = sDate. getDate (); var eYear = sYear; var eMonth = sMonth + num; var eDay = sDay; while (eMonth> 12) {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 calcDate () {var d = document. getElementById ('date '). value; var n = document. getElementById ('num '). value; var eDate = addMonth (d, n); document. getElementById ('result '). innerHTML = eDate. getFullYear () + '-' + (eDate. getMonth () + 1) + '-' + eDate. getDate ();} script        

Method 2:

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.