如果在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中有这种行为的参考。这是一个可靠的跨浏览器功能吗?或者我应该看看其他的方法吗?
当前回答
我觉得这对我来说是最好的解决办法。让Date对象为您计算它。
var today = new Date();
var lastDayOfMonth = new Date(today.getFullYear(), today.getMonth()+1, 0);
将day参数设置为0表示比本月的第一天小一天,即上个月的最后一天。
其他回答
这将给你当月的最后一天。
注:在ios设备上包含时间。 # gshoanganh
var date = new Date();
console.log(new Date(date.getFullYear(), date.getMonth() + 1, 0, 23, 59, 59));
我将使用一个中间日期与下个月的第一天,并返回前一天的日期:
int_d = new Date(2008, 11+1,1);
d = new Date(int_d - 1);
对lebreeze提供的解决方案稍加修改:
function daysInMonth(iMonth, iYear)
{
return new Date(iYear, iMonth, 0).getDate();
}
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);
如果你需要精确的以毫秒为单位的月底(例如时间戳):
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 ())