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
2009-03-03 04:31:55
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
2009-03-03 04:40:20
It wouldn't fail if he setDate(1) before doing the setMonth()
Paolo Bergantino
2009-03-03 04:46:08
Yes, that works nicely.
Shog9
2009-03-03 04:49:57
+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
2009-03-03 04:34:30
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
2009-03-03 04:39:37
You're neglecting the fact that setMonth will wrap values. Prestaul's answer works fine for January.
overslacked
2009-03-03 04:39:53
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
2009-03-03 04:44:31
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
2009-03-03 04:50:02
I agree. You'll get my vote as well if you remove the test for January.
Prestaul
2009-03-03 04:54:57
As you wish ... I had to check it was okay in the constructor as well, rather than just for setMonth().
paxdiablo
2009-03-03 05:00:23
+1... I love StackOverflow because the best answer usually does find its way to the top!
Prestaul
2009-03-03 05:02:39
A:
JavaScript Get Month
http://java.pakcarid.com/Cpp.aspx?sub=373&ff=2976&topid=39&sls=25
lois
2010-10-23 07:43:47