Possible Duplicate:
What is the best way to determine the number of days in a month with javascript?
Say I have the month as a number and a year.
Possible Duplicate:
What is the best way to determine the number of days in a month with javascript?
Say I have the month as a number and a year.
// Month in JavaScript is 0-indexed (January is 0, February is 1, etc),
// but by using 0 as the day it will give us the last day of the prior
// month. So passing in 1 as the month number will return the last day
// of January, not February
function daysInMonth (month, year) {
return new Date(year, month, 0).getDate();
}
// July
daysInMonth(7,2009); // 31
// February
daysInMonth(2,2009); // 28
daysInMonth(2,2008); // 29
0
as the day is that it returns the last day of the last month, so you have to add 1
to it to return the correct amount of days when using month = new Date().getMonth()
Date.prototype.monthDays= function(){
var d= new Date(this.getFullYear(), this.getMonth()+1, 0);
return d.getDate();
}
new Date(year, month, 0)
will produce the last month's last day, so adding + 1
to the parameters results in the current month's days. I'm not correcting anything here. I'm trying to make sure I understand, and I believe kennebec's answer here is the correct answer.
The following takes any valid datetime value and returns the number of days in the associated month... it eliminates the ambiguity of both other answers...
// pass in any date as parameter anyDateInMonth
function daysInMonth(anyDateInMonth) {
return new Date(anyDateInMonth.getFullYear(),
anyDateInMonth.getMonth()+1,
0).getDate();}
++anyDateInMonth.getMonth()
to anyDateInMonth.getMonth() + 1
Mar 12, 2015 at 19:38
++(anyDateInMonth.getMonth())
??
Mar 12, 2015 at 22:06
++
JavaScript is expecting you to be using it to increment a mutable value such as one stored in a variable. For example you can't do ++5
but you can do var x = 5; ++x
. So in your function, if you don't want to use a variable, you'll have to actually add 1.
Mar 13, 2015 at 17:53
Another possible option would be to use Datejs
Then you can do
Date.getDaysInMonth(2009, 9)
Although adding a library just for this function is overkill, it's always nice to know all the options you have available to you :)
const d = (y, m) => new Date(y, m, 0).getDate();