如果在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中有这种行为的参考。这是一个可靠的跨浏览器功能吗?或者我应该看看其他的方法吗?
当前回答
如果你需要精确的以毫秒为单位的月底(例如时间戳):
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 ())
其他回答
我觉得这对我来说是最好的解决办法。让Date对象为您计算它。
var today = new Date();
var lastDayOfMonth = new Date(today.getFullYear(), today.getMonth()+1, 0);
将day参数设置为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));
}
我将使用一个中间日期与下个月的第一天,并返回前一天的日期:
int_d = new Date(2008, 11+1,1);
d = new Date(int_d - 1);
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);
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作为上个月的最后一天并不意味着它们会继续这样做,或者没有列出的浏览器会这样做,但它使人们相信它应该在每个浏览器中以相同的方式工作。