2013-08-30 161 views
2

我的jQuery函数需要current month。我想根据点击的按钮显示下个月和上个月。使用jQuery查找下个月和上个月

我的问题是,有没有defaultDate()函数我可以打电话来了解当前月份的下个月和前几个月?

$(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()); 
}); 
+0

http://momentjs.com/ – CodingIntrigue

回答

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。

+0

这有帮助。非常感谢你:) – user2354302

+1

我设置了 - 'new Date()。setMonth(new Date()。getMonth()+ 2,1)',我得到了 - '1404212502044'。这个数字是什么,以及如何提取和显示月份? – arjun