如何使用JavaScript查找下个月和前几个月

How to find the next and previous months with JavaScript?

本文关键字:几个月 下个月 查找 何使用 JavaScript      更新时间:2023-09-26

My 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());
});

如果你只想得到下个月的第一天,你可以做这样的事情:

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。