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

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

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


当前回答

这对我很有用。 将提供给定年份和月份的最后一天:

var d = new Date(2012,02,0);
var n = d.getDate();
alert(n);

其他回答

下面的函数给出了这个月的最后一天:

函数getLstDayOfMonFnc(date) { 返回new Date(Date . getfullyear (), Date . getmonth (), 0).getDate() } console.log(getLstDayOfMonFnc(new Date(2016, 2,15))) //输出:29 console.log(getLstDayOfMonFnc(new Date(2017,2,15))) //输出:28 console.log(getLstDayOfMonFnc(new Date(2017,11,15))) //输出:30 console.log(getLstDayOfMonFnc(new Date(2017,12,15))) //输出:31

类似地,我们可以得到这个月的第一天:

函数getFstDayOfMonFnc(日期){ 返回new Date(Date . getfullyear (), Date . getmonth (), 1).getDate() } console.log(getFstDayOfMonFnc(new Date(2016, 2,15))) //输出

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

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)); 
}

这对我很有用。 将提供给定年份和月份的最后一天:

var d = new Date(2012,02,0);
var n = d.getDate();
alert(n);