使用jQuery查找下一个和前几个月

use*_*302 2 jquery date monthcalendar

我的jQuery函数接受了current month.我想根据点击的按钮显示下个月和前几个月.

我的问题是,是否有一个default Date()功能我可以打电话来了解当月的下个月和前几个月?

$(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
    });
});
Run Code Online (Sandbox Code Playgroud)

我可以编写一些代码并获得下一个和前几个月,但我想知道是否已经defined functions为此目的了?

解决了

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());
});
Run Code Online (Sandbox Code Playgroud)

Dan*_*ank 8

如果您只想获得下个月的第一天,您可以执行以下操作:

var now = new Date();
var future = now.setMonth(now.getMonth() + 1, 1);
var past = now.setMonth(now.getMonth() - 1, 1);
Run Code Online (Sandbox Code Playgroud)

这将阻止"下个月"跳过一个月(例如,如果省略第二个参数,则在2014年1月31日添加一个月将导致2014年3月3日).

另外,使用date.js*可以执行以下操作:

var today = Date.today();
var past = Date.today().add(-1).months();
var future = Date.today().add(1).months();
Run Code Online (Sandbox Code Playgroud)

在这个例子中,我使用今天的日期,但它适用于任何日期.

*date.js已被放弃.如果你决定使用一个库,你应该像RGraham建议的那样使用moment.js.