Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Marty Hitchcock
Marty Hitchcock
13,108 Points

JS Date objects - changing months

I am trying to make a calendar type web app and could use some help! What I am trying to do is change from one month to another. I have set up the core of what I am having trouble with here: http://jsfiddle.net/w55yy2fd/7/

What I am stuck on is trying to get to the previous month. I need to be able to display all the days of that month and the name of it. I have got that all working fine for the current month but I can't change the month itself.

As you can see, when I try to set a new month it is giving me a nice long number which doesn't really help me. Where as I can get the right number with the getMonth method but I can not change it.

Can anyone tell me how to make it so the h1 in my example changes each time the button is pressed?

2 Answers

Mark Josephsen
Mark Josephsen
8,803 Points

From the looks of your code, you're wanting the number to decrease? Anyhow, that is what this does. The h1 decrements by 1 each time the button is pressed:

var date = new Date();
var gMonth = date.getMonth();
var sMonth = gMonth;

var assignMonth = $('#month').append(gMonth);

var prvMonth = function(){
    sMonth--;
    $('#month').text(sMonth);
}

$('#btn').on("click", prvMonth);

I hope this helps in some way!

Marty Hitchcock
Marty Hitchcock
13,108 Points

Thanks! Pretty sure that will do the trick.

Here is a version of what you're trying to do, just edit to use your button etc.

//Set new date
var d = new Date();
//Get current date
var current = d.getMonth();
//Set date to current date
d.setMonth(current);
//Console log for view of current date
console.log(d);
//Make previous month
function prvMonth() {
//Take current date, subtract by one. (Month dates are held in integers in javascript)
    d.setMonth(current - 1);
//Console log to see changed date
    console.log(d);
}
//call function
prvMonth();

Hope this helps!

Marty Hitchcock
Marty Hitchcock
13,108 Points

Thanks for that. But there are a few things that isn't doing which I need it to do. 1 - It gives a full date value, where as I need to get the month value. 2 - It keeps giving the same month back instead of being one less.