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

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

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


当前回答

const today = new Date();

let beginDate = new Date();

let endDate = new Date();

// fist date of montg

beginDate = new Date(

  `${today.getFullYear()}-${today.getMonth() + 1}-01 00:00:00`

);

// end date of month 

// set next Month first Date

endDate = new Date(

  `${today.getFullYear()}-${today.getMonth() + 2}-01 :23:59:59`

);

// deducting 1 day

endDate.setDate(0);

其他回答

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(去年);

我觉得这对我来说是最好的解决办法。让Date对象为您计算它。

var today = new Date();
var lastDayOfMonth = new Date(today.getFullYear(), today.getMonth()+1, 0);

将day参数设置为0表示比本月的第一天小一天,即上个月的最后一天。

我的同事偶然发现了以下可能是一个更简单的解决方案

function daysInMonth(iMonth, iYear)
{
    return 32 - new Date(iYear, iMonth, 32).getDate();
}

窃取自http://snippets.dzone.com/posts/show/2099

对lebreeze提供的解决方案稍加修改:

function daysInMonth(iMonth, iYear)
{
    return new Date(iYear, iMonth, 0).getDate();
}