如果在Date中提供0作为dayValue。setFullYear你会得到上个月的最后一天:

d = new Date(); d.setFullYear(2008, 11, 0); //  Sun Nov 30 2008

在mozilla中有这种行为的参考。这是一个可靠的跨浏览器功能吗?或者我应该看看其他的方法吗?


当前回答

对我来说,这段代码很有用

end_date = new Date(2018, 3,1).toISOString().split('T')[0] console.log (end_date)

其他回答

我知道这只是一个语义问题,但我最终以这种形式使用它。

var lastDay = new Date(new Date(2008, 11+1,1) - 1).getDate();
console.log(lastDay);

因为函数是从内部参数向外解析的,所以工作原理是一样的。

然后,您可以用所需的详细信息替换年和月/年,无论它来自当前日期。或者一个特定的月/年。

如果你需要精确的以毫秒为单位的月底(例如时间戳):

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 ())

对我来说,这段代码很有用

end_date = new Date(2018, 3,1).toISOString().split('T')[0] console.log (end_date)

试试这个。

lastDateofTheMonth = new Date(year, month, 0)

例子:

new Date(2012, 8, 0)

输出:

Date {Fri Aug 31 2012 00:00:00 GMT+0900 (Tokyo Standard Time)}
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)); 
}