admin管理员组文章数量:1313797
function GetDaysInMonth(month, year)
{
return 32 - new Date(year, month, 32).getDate();
}
Ok, I don't see what this is doing specifically, this part:
new Date(year, month, 32).getDate();
I know what getDate()
does, but then I looked up Date
in JavaScript but in this particular example, I don't see why you'd pass 32 here. How can this be returning the number of days in whatever month and year you're passing to it?
function GetDaysInMonth(month, year)
{
return 32 - new Date(year, month, 32).getDate();
}
Ok, I don't see what this is doing specifically, this part:
new Date(year, month, 32).getDate();
I know what getDate()
does, but then I looked up Date
in JavaScript but in this particular example, I don't see why you'd pass 32 here. How can this be returning the number of days in whatever month and year you're passing to it?
- actually it's returning 31 for february so the fing thing doesn't even work. I'm just pissed because my boss just tells me how to reduce 30 lines of code but then the fing function he tells me to use doesn't even work! Not that I can't fix it but you know how conceded asswipes are about code reviews sometimes. – PositiveGuy Commented Nov 6, 2009 at 18:45
- I should have just looked up this method, it was stolen: snippets.dzone./posts/show/2099 – PositiveGuy Commented Nov 6, 2009 at 18:55
3 Answers
Reset to default 12The "32nd day" of any month will roll over to the next one. If there are 31 days in a month, the "32nd day" will be the 1st of the next month. If there are 30, the "32nd day" will be the 2nd of the next month. If there are 28, the "32nd day" will be the 4th of the next month.
Subtract any of these from 32 and you get the correct number.
Date.prototype.monthDays: function(){
var d= new Date(this.getFullYear(), this.getMonth()+1, 0);
return d.getDate();
}
The zero date of next month is the last date of this month...
alert(new Date().monthDays())// any date object
Try this:
function GetDaysInMonth(month, year) {
return (new Date(new Date(year, month, 1, 0, 0, 0, 0)-86400000)).getDate();
}
This is using the first day of the preceeding month and substracts one day (86400000 milloseconds) from it to get the last day of the given month. Note that the Date
’s month parameter expects values from 0 (January) to 11 (December). But for GetDaysInMonth
use 1 (January) to 12 (December):
GetDaysInMonth(12, 2007) // returns 31
GetDaysInMonth(1, 2008) // returns 31
GetDaysInMonth(2, 2008) // returns 29
If you want to use the same values as for Date
, use new Date(year, month+1, 1, 0, 0, 0, 0)
instead.
本文标签: javascriptHow does this quotdays in monthquot function workStack Overflow
版权声明:本文标题:javascript - How does this "days in month" function work? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741956063a2406994.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论