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

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

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


当前回答

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

函数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))) //输出

其他回答

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

函数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))) //输出

如何不这样做

这个月最后一个月的答案可能是这样的:

var last = new Date(date)
last.setMonth(last.getMonth() + 1) // This is the wrong way to do it.
last.setDate(0)

这适用于大多数日期,但如果日期已经是该月的最后一天,而该月的天数比下一个月多,则会失败。

例子:

假设日期是07/31/21。

然后last.setMonth(last.getMonth() + 1)增加月份,但保持日期设置为31。

你得到08/31/21的Date对象,

实际上是21年9月1日。

所以last.setDate(0)的结果是08/31/21,而我们真正想要的是07/31/21。

我将使用一个中间日期与下个月的第一天,并返回前一天的日期:

int_d = new Date(2008, 11+1,1);
d = new Date(int_d - 1);

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

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

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

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

设置你需要日期的月份,然后将日期设置为0,所以在date函数中,月份从1 - 31开始,然后得到最后一天^^

var last = new Date(new Date(new Date().setMonth(7)).setDate(0)).getDate(); console.log(去年);