如果在Date中提供0作为dayValue。setFullYear你会得到上个月的最后一天:
d = new Date(); d.setFullYear(2008, 11, 0); // Sun Nov 30 2008
在mozilla中有这种行为的参考。这是一个可靠的跨浏览器功能吗?或者我应该看看其他的方法吗?
如果在Date中提供0作为dayValue。setFullYear你会得到上个月的最后一天:
d = new Date(); d.setFullYear(2008, 11, 0); // Sun Nov 30 2008
在mozilla中有这种行为的参考。这是一个可靠的跨浏览器功能吗?或者我应该看看其他的方法吗?
当前回答
我知道这只是一个语义问题,但我最终以这种形式使用它。
var lastDay = new Date(new Date(2008, 11+1,1) - 1).getDate();
console.log(lastDay);
因为函数是从内部参数向外解析的,所以工作原理是一样的。
然后,您可以用所需的详细信息替换年和月/年,无论它来自当前日期。或者一个特定的月/年。
其他回答
对lebreeze提供的解决方案稍加修改:
function daysInMonth(iMonth, iYear)
{
return new Date(iYear, iMonth, 0).getDate();
}
我的同事偶然发现了以下可能是一个更简单的解决方案
function daysInMonth(iMonth, iYear)
{
return 32 - new Date(iYear, iMonth, 32).getDate();
}
窃取自http://snippets.dzone.com/posts/show/2099
function getLastDay(y, m) {
return 30 + (m <= 7 ? ((m % 2) ? 1 : 0) : (!(m % 2) ? 1 : 0)) - (m == 2) - (m == 2 && y % 4 != 0 || !(y % 100 == 0 && y % 400 == 0));
}
设置你需要日期的月份,然后将日期设置为0,所以在date函数中,月份从1 - 31开始,然后得到最后一天^^
var last = new Date(new Date(new Date().setMonth(7)).setDate(0)).getDate(); console.log(去年);
如果你需要精确的以毫秒为单位的月底(例如时间戳):
d = new Date() console.log (d.toString ()) d.setDate (1) d.setHours(23, 59, 59, 999) d.setMonth(d.getMonth() + 1) d.setDate(d.getDate() - 1) console.log (d.toString ())