如果在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中有这种行为的参考。这是一个可靠的跨浏览器功能吗?或者我应该看看其他的方法吗?
当前回答
设置你需要日期的月份,然后将日期设置为0,所以在date函数中,月份从1 - 31开始,然后得到最后一天^^
var last = new Date(new Date(new Date().setMonth(7)).setDate(0)).getDate(); console.log(去年);
其他回答
这将给出本月的第一天和最后一天。
如果你需要改变“年份”,删除d.getFullYear()并设置你的年份。
如果需要更改“month”,则删除d.getMonth()并设置年份。
var = new Date() 瓦尔日=[“星期日”、“星期一”、“星期二”、“星期三”、“星期五”、“星期六”]; var fistdaymoon = day[(新日期[d. getllyear], d.getMonth(), 1 .getDay [) var lastyousmonth = day[(新日期[d.getFullYear], d.getMonth() + 1, 0).getDay() 控制台(“第一天: 控制台(“最后一天:” 警告(“第一天:”+“嘶嘶声”); 警告(“最后一天:”+ lastdamonth);
Var月= 0;/ / 1月 var d = new日期(2008,月份+ 1,0); console.log (d.toString ());// 1月的最后一天
IE 6: Thu Jan 31 00:00:00 CST 2008
IE 7: Thu Jan 31 00:00:00 CST 2008
IE 8: Beta 2: Thu Jan 31 00:00:00 CST 2008
Opera 8.54: Thu, 31 Jan 2008 00:00:00 GMT-0600
Opera 9.27: Thu, 31 Jan 2008 00:00:00 GMT-0600
Opera 9.60: Thu Jan 31 2008 00:00:00 GMT-0600
Firefox 2.0.0.17: Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time)
Firefox 3.0.3: Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time)
Google Chrome 0.2.149.30: Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time)
Safari for Windows 3.1.2: Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time)
输出差异是由于toString()实现的差异,而不是由于日期不同。
当然,仅仅因为上面列出的浏览器使用0作为上个月的最后一天并不意味着它们会继续这样做,或者没有列出的浏览器会这样做,但它使人们相信它应该在每个浏览器中以相同的方式工作。
下面是一个保留GMT时间和初始日期时间的答案
var date = new Date(); var first_date = new Date(date); //Make a copy of the date we want the first and last days from first_date.setUTCDate(1); //Set the day as the first of the month var last_date = new Date(first_date); //Make a copy of the calculated first day last_date.setUTCMonth(last_date.getUTCMonth() + 1); //Add a month last_date.setUTCDate(0); //Set the date to 0, this goes to the last day of the previous month console.log(first_date.toJSON().substring(0, 10), last_date.toJSON().substring(0, 10)); //Log the dates with the format yyyy-mm-dd
这个很好用:
Date.prototype.setToLastDateInMonth = function () {
this.setDate(1);
this.setMonth(this.getMonth() + 1);
this.setDate(this.getDate() - 1);
return this;
}
对lebreeze提供的解决方案稍加修改:
function daysInMonth(iMonth, iYear)
{
return new Date(iYear, iMonth, 0).getDate();
}