views:

2586

answers:

3

I've been using Javascript's Date for a project, but noticed today that my code that previously worked is no longer working correctly. Instead of producing Feb as expected, the code below produces March.

My code looks something like this:

current = new Date();
current.setMonth(current.getMonth()+1); //If today is Jan, expect it to be Feb now

This code worked everyday up until today. Is this a Javascript bug or am I going about this the wrong way?

+5  A: 

You'll probably find you're setting the date to Feb 31, 2009 (if today is Jan 31) and Javascript automagically rolls that into the early part of March.

Check the day of the month, I'd expect it to be 1, 2 or 3. If it's not the same as before you added a month, roll back by one day until the month changes again.

That way, the day "last day of Jan" becomes "last day of Feb".

EDIT:

Ronald, based on your comments to other answers, you might want to steer clear of edge-case behavior such as "what happens when I try to make Feb 30" or "what happens when I try to make 2009/13/07 (yyyy/mm/dd)" (that last one might still be a problem even for my solution, so you should test it).

Instead, I would explicitly code for the possibilities. Since you don't care about the day of the month (you just want the year and month to be correct for next month), something like this should suffice:

now = new Date();
if (now.getMonth() == 11) {
    current = new Date(now.getYear() + 1, 0, 1);
} else {
    current = new Date(now.getYear(), now.getMonth() + 1, 1);
}

That gives you Jan 1 the following year for any day in December and the first day of the following month for any other day. More code, I know, but I've long since grown tired of coding tricks for efficiency, preferring readability unless there's a clear requirement to do otherwise.

paxdiablo
Of course, it's worth mentioning that all of this depends on what your computer's date is set to. It's rarely accurate.
Josh Stodola
Good one, @Josh :-) - mine's not normally out by more than a few minutes. I can't vouch for anyone else. Perhaps I should adjust the answer to read "will give you the first day of the month following **the month your computer thinks it is**.
paxdiablo
+2  A: 

Instead, try:

now = new Date();
current = new Date(now.getYear(), now.getMonth()+1, 1);
Brannon
This appears to be working if I do current.getMonth()+1 after using your code. Thanks!
Keep in mind this sets the day of the month back to 1 - is this what you wanted?
paxdiablo
All I want to do is get to the next month from the current month. I don't care about the days, I just need the month to be accurate.
Actually I need the year to be accurate too..
A: 

Is there a way to change the time zone from GMT to EST?

Time zone should be determined from the client
Slace