Javascript Date: next month

后端 未结 8 1468
情深已故
情深已故 2020-11-28 10:01

I\'ve been using Javascript\'s Date for a project, but noticed today that my code that previously worked is no longer working correctly. Instead of producing Feb as expected

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 10:21

    If you use moment.js, they have an add function. Here's the link - https://momentjs.com/docs/#/manipulating/add/

    moment().add(7, 'months');
    

    I also wrote a recursive function based on paxdiablo's answer to add a variable number of months. By default this function would add a month to the current date.

    function addMonths(after = 1, now = new Date()) {
            var current;
            if (now.getMonth() == 11) {
                current = new Date(now.getFullYear() + 1, 0, 1);
            } else {
                current = new Date(now.getFullYear(), now.getMonth() + 1, 1);            
            }
            return (after == 1) ? current : addMonths(after - 1, new Date(now.getFullYear(), now.getMonth() + 1, 1))
        }
    

    Example

    console.log('Add 3 months to November', addMonths(3, new Date(2017, 10, 27)))
    

    Output -

    Add 3 months to November Thu Feb 01 2018 00:00:00 GMT-0800 (Pacific Standard Time)
    

提交回复
热议问题