Search code examples
javascriptjquerydatemonthcalendar

How to find the next and previous months with JavaScript?


My jQuery function takes in the current month. I would like to display the next and previous months depending on the buttons clicked.

My question is, is there a default Date() function I can call to know the next and previous months of a current month ?

$(document).ready(function () {
    var current_date = $('#cal-current-month').html();
    //current_date will have September 2013
    $('#previous-month').onclick(function(){
        // Do something to get the previous month
    });
    $('#next-month').onclick(function(){
        // Do something to get the previous month
    });
});

I can write some code and get the next and previous months, but I was wondering if there is any already defined functions for this purpose?

SOLVED

var current_date = $('.now').html();
var now = new Date(current_date);

var months = new Array( "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

$('#previous-month').click(function(){
    var past = now.setMonth(now.getMonth() -1);
    $('.now').html(months[now.getMonth()]+' '+now.getFullYear());
});

$('#next-month').click(function(){
    var future = now.setMonth(now.getMonth() +1);
    $('.now').html(months[now.getMonth()]+' '+now.getFullYear());
});

Solution

  • If you just want to get the first day of the next month, you could do something like:

    var now = new Date();
    var future = now.setMonth(now.getMonth() + 1, 1);
    var past = now.setMonth(now.getMonth() - 1, 1);
    

    This will prevent the "next" month from skipping a month (e.g. adding a month to January 31, 2014 will result in March 3rd, 2014 if you omit the second parameter).

    As an aside, using date.js* you could do the following:

    var today = Date.today();
    var past = Date.today().add(-1).months();
    var future = Date.today().add(1).months();
    

    In this example I am using today's date, but it works for any date.

    *date.js has been abandoned. If you decide to use a library, you should probably use moment.js as RGraham suggests.