Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
170
rated 0 times [  176] [ 6]  / answers: 1 / hits: 25182  / 11 Years ago, fri, august 30, 2013, 12:00:00

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

More From » jquery

 Answers
4

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.


[#76005] Thursday, August 29, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leiaf

Total Points: 10
Total Questions: 101
Total Answers: 84

Location: Guam
Member since Tue, Nov 29, 2022
2 Years ago
leiaf questions
Sat, Mar 27, 21, 00:00, 3 Years ago
Wed, Apr 3, 19, 00:00, 5 Years ago
Wed, Jan 16, 19, 00:00, 6 Years ago
;