2

我的 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
    });
});

我可以编写一些代码并获得下个月和前几个月,但我想知道是否已经有任何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());
});
4

1 回答 1

8

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

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

这将防止“下”月跳过一个月(例如,如果省略第二个参数,则将一个月添加到 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();

在此示例中,我使用的是今天的日期,但它适用于任何日期。

*date.js 已被废弃。如果您决定使用库,您可能应该按照 RGraham 的建议使用 moment.js。

于 2013-08-30T19:31:13.750 回答