如果在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中有这种行为的参考。这是一个可靠的跨浏览器功能吗?或者我应该看看其他的方法吗?
当前回答
对我来说,这段代码很有用
end_date = new Date(2018, 3,1).toISOString().split('T')[0] console.log (end_date)
其他回答
如何不这样做
这个月最后一个月的答案可能是这样的:
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。
对lebreeze提供的解决方案稍加修改:
function daysInMonth(iMonth, iYear)
{
return new Date(iYear, iMonth, 0).getDate();
}
这将给出本月的第一天和最后一天。
如果你需要改变“年份”,删除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);
这将给你当月的最后一天。
注:在ios设备上包含时间。 # gshoanganh
var date = new Date();
console.log(new Date(date.getFullYear(), date.getMonth() + 1, 0, 23, 59, 59));
如果你只需要得到一个月的最后一个日期,下面的工作为我。
var d = new Date();
const year = d.getFullYear();
const month = d.getMonth();
const lastDay = new Date(year, month +1, 0).getDate();
console.log(lastDay);
在这里试试https://www.w3resource.com/javascript-exercises/javascript-date-exercise-9.php