JavaScript function to add X months to a date

后端 未结 19 2088
星月不相逢
星月不相逢 2020-11-22 02:44

I’m looking for the easiest, cleanest way to add X months to a JavaScript date.

I’d rather not handle the rolling over of the year or have to write my own function.<

相关标签:
19条回答
  • 2020-11-22 03:12

    I'm using moment.js library for date-time manipulations. Sample code to add one month:

    var startDate = new Date(...);
    var endDateMoment = moment(startDate); // moment(...) can also be used to parse dates in string format
    endDateMoment.add(1, 'months');
    
    0 讨论(0)
  • 2020-11-22 03:15

    As demonstrated by many of the complicated, ugly answers presented, Dates and Times can be a nightmare for programmers using any language. My approach is to convert dates and 'delta t' values into Epoch Time (in ms), perform any arithmetic, then convert back to "human time."

    // Given a number of days, return a Date object
    //   that many days in the future. 
    function getFutureDate( days ) {
    
        // Convert 'days' to milliseconds
        var millies = 1000 * 60 * 60 * 24 * days;
    
        // Get the current date/time
        var todaysDate = new Date();
    
        // Get 'todaysDate' as Epoch Time, then add 'days' number of mSecs to it
        var futureMillies = todaysDate.getTime() + millies;
    
        // Use the Epoch time of the targeted future date to create
        //   a new Date object, and then return it.
        return new Date( futureMillies );
    }
    
    // Use case: get a Date that's 60 days from now.
    var twoMonthsOut = getFutureDate( 60 );
    

    This was written for a slightly different use case, but you should be able to easily adapt it for related tasks.

    EDIT: Full source here!

    0 讨论(0)
  • 2020-11-22 03:18

    The following function adds months to a date in JavaScript (source). It takes into account year roll-overs and varying month lengths:

    function addMonths(date, months) {
        var d = date.getDate();
        date.setMonth(date.getMonth() + +months);
        if (date.getDate() != d) {
          date.setDate(0);
        }
        return date;
    }
    
    // Add 12 months to 29 Feb 2016 -> 28 Feb 2017
    console.log(addMonths(new Date(2016,1,29),12).toString());
    
    // Subtract 1 month from 1 Jan 2017 -> 1 Dec 2016
    console.log(addMonths(new Date(2017,0,1),-1).toString());
    
    // Subtract 2 months from 31 Jan 2017 -> 30 Nov 2016
    console.log(addMonths(new Date(2017,0,31),-2).toString());
    
    // Add 2 months to 31 Dec 2016 -> 28 Feb 2017
    console.log(addMonths(new Date(2016,11,31),2).toString());

    The above solution covers the edge case of moving from a month with a greater number of days than the destination month. eg.

    • Add twelve months to February 29th 2020 (should be February 28th 2021)
    • Add one month to August 31st 2020 (should be September 30th 2020)

    If the day of the month changes when applying setMonth, then we know we have overflowed into the following month due to a difference in month length. In this case, we use setDate(0) to move back to the last day of the previous month.

    Note: this version of this answer replaces an earlier version (below) that did not gracefully handle different month lengths.

    var x = 12; //or whatever offset
    var CurrentDate = new Date();
    console.log("Current date:", CurrentDate);
    CurrentDate.setMonth(CurrentDate.getMonth() + x);
    console.log("Date after " + x + " months:", CurrentDate);
    
    0 讨论(0)
  • 2020-11-22 03:18

    Sometimes useful create date by one operator like in BIRT parameters

    I made 1 month back with:

    new Date(new Date().setMonth(new Date().getMonth()-1));   
    
    0 讨论(0)
  • 2020-11-22 03:21

    Simple solution: 2678400000 is 31 day in milliseconds

    var oneMonthFromNow = new Date((+new Date) + 2678400000);
    

    Update:

    Use this data to build our own function:

    • 2678400000 - 31 day
    • 2592000000 - 30 days
    • 2505600000 - 29 days
    • 2419200000 - 28 days
    0 讨论(0)
  • 2020-11-22 03:21

    Just to add on to the accepted answer and the comments.

    var x = 12; //or whatever offset
    var CurrentDate = new Date();
    
    //For the very rare cases like the end of a month
    //eg. May 30th - 3 months will give you March instead of February
    var date = CurrentDate.getDate();
    CurrentDate.setDate(1);
    CurrentDate.setMonth(CurrentDate.getMonth()+X);
    CurrentDate.setDate(date);
    
    0 讨论(0)
提交回复
热议问题