JavaScript function to add X months to a date

后端 未结 19 2103
星月不相逢
星月不相逢 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: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!

提交回复
热议问题