tags:

views:

1414

answers:

3

Given a date object, how to get its previous month's first day in javascript

+4  A: 
function firstDayInPreviousMonth(yourDate) {
    var d = new Date(yourDate);
    d.setDate(1);
    d.setMonth(d.getMonth() - 1);
    return d;
}

EDIT: Alright... I've definitely learned something here. I think that this is the simplest solution that covers all cases (and yes, it does work for January):

function firstDayInPreviousMonth(yourDate) {
    return new Date(yourDate.getYear(), yourDate.getMonth() - 1, 1);
}
Prestaul
Note that this will FAIL for something like: firstDayInPreviousMonth(new Date("Mar 31 2009")). See the comments on: http://stackoverflow.com/questions/499838/javascript-date-next-month
Shog9
It wouldn't fail if he setDate(1) before doing the setMonth()
Paolo Bergantino
Yes, that works nicely.
Shog9
+3  A: 

The following should work:

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

keeping in mind that months are zero-based so December is 11 rather than 12.

But, as others have pointed out, the month wraps, even as part of the atomic constructor, so the following is also possible:

now = new Date();
firstDayPrevMonth = new Date(now.getYear(), now.getMonth() - 1, 1);
paxdiablo
I like this approach, but your solution actually isn't correct. When getMonth() == 1, the month is February. You want to check for getMonth() == 0, and even that isn't required because the Date constructor will accept negative values and work correctly.
Prestaul
You're neglecting the fact that setMonth will wrap values. Prestaul's answer works fine for January.
overslacked
Yes, but not for moving back to a month where the number of days is less, unfortunately. It's better to construct the new date atomically rather than piecemeal.
paxdiablo
Considering the Mar 31 example, you are correct about the anatomical date construction - if you change your answer (I do find the "blindly subtracting a month" line to be misleading given javascript's setXXX wrapping) I'll be happy to adjust my vote on this answer.
overslacked
Done, overslacked.
paxdiablo
I agree. You'll get my vote as well if you remove the test for January.
Prestaul
As you wish ... I had to check it was okay in the constructor as well, rather than just for setMonth().
paxdiablo
+1... I love StackOverflow because the best answer usually does find its way to the top!
Prestaul