Let's say I have 3 variables like this:
var Month = 8; // in reality, it's a parameter provided by some user input
var Year = 2011; // same here
var FirstDay = new Date(Year, Month, 1);
Now I want to have the value of the day before the first day of the month in a variable. I'm doing this:
var LastDayPrevMonth = (FirstDay.getDate() - 1);
It's not working as planned. What the right of doing it?
Thanks.
Let's say I have 3 variables like this:
var Month = 8; // in reality, it's a parameter provided by some user input
var Year = 2011; // same here
var FirstDay = new Date(Year, Month, 1);
Now I want to have the value of the day before the first day of the month in a variable. I'm doing this:
var LastDayPrevMonth = (FirstDay.getDate() - 1);
It's not working as planned. What the right of doing it?
Thanks.
Share Improve this question asked Sep 19, 2011 at 3:16 frenchiefrenchie 51.9k117 gold badges319 silver badges525 bronze badges5 Answers
Reset to default 15var LastDayPrevMonth = new Date(Year, Month, 0).getDate();
var LastDayPrevMonth = new Date(FirstDay);
LastDayPrevMonth.setHours(FirstDay.getHours()-24);
var FirstDay = new Date(Year, Month, 1);
var lastMonth = new Date(FirstDay);
lastMonth.setDate(-1);
alert(lastMonth);
And remember that 8 is Sept, not Aug in JavaScript. :)
If you need to calculate this based on today's date ( you want the last day of last month ), the following should help.
If you only care about the month/day/year, this is the simplest and fastest that I can think of:
var d = new Date(); d.setDate(0);
console.log(d);
If you want midnight of last day of the previous month, then:
var d = new Date(); d.setDate(0); d.setHours(0,0,0,0);
console.log(d);
If you want to know the last day of the previous month, based on provided year/month:
var year = 2016, month = 11;
var d = new Date(year, (month - 1)); d.setDate(0); d.setHours(0,0,0,0);
console.log(d);
After running any of the above, to get the YYYY-M-D format:
var str = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
console.log(str);
To see additional methods available, and to see what they do, you can read the docs.
Create a new Date
object and pass it the other date coerced to the number of milliseconds since the Unix epoch and then minus a whole day (in milliseconds).
var LastDayPrevMonth = new Date(FirstDay - 864e5);
Example:
var Month = 8; // in reality, it's a parameter provided by some user input
var Year = 2011; // same here
var FirstDay = new Date(Year, Month, 1);
var LastDayPrevMonth = new Date(FirstDay - 864e5);
document.body.innerHTML = LastDayPrevMonth;