Javascript 如何获得本月的最后一天
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1924815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get last day of the month
提问by Rod
How can I obtain the last day of the month with the timestamp being 11:59:59 PM?
如何获取时间戳为晚上 11:59:59 的月份的最后一天?
回答by miku
function LastDayOfMonth(Year, Month) {
return new Date((new Date(Year, Month, 1)) - 1);
}
console.log(LastDayOfMonth(2009, 11))
Example:
例子:
> LastDayOfMonth(2009, 11)
Mon Nov 30 2009 23:59:59 GMT+0100 (CET)
回答by Chetan Sastry
This will give you last day of current month.
这会给你当月的最后一天。
var t= new Date();
alert(new Date(t.getFullYear(), t.getMonth() + 1, 0, 23, 59, 59));
回答by csukcc
var d = new Date();
console.log(d);
d.setMonth(d.getMonth() + 1); // set month as next month
console.log(d);
d.setDate(0); // get the last day of previous month
console.log(d);
Here is output from the code above:
Thu Oct 03 2013 11:34:59 GMT+0100 (GMT Daylight Time)
Sun Nov 03 2013 11:34:59 GMT+0000 (GMT Standard Time)
Thu Oct 31 2013 11:34:59 GMT+0000 (GMT Standard Time)
以下是上述代码的输出:
Thu Oct 03 2013 11:34:59 GMT+0100 (GMT Daylight Time)
Sun Nov 03 2013 11:34:59 GMT+0000 (GMT Standard Time)
Thu Oct 31 2013 11:34: 59 GMT+0000(GMT 标准时间)
回答by jare25
var d = new Date();
m = d.getMonth(); //current month
y = d.getFullYear(); //current year
alert(new Date(y,m,1)); //this is first day of current month
alert(new Date(y,m+1,0)); //this is last day of current month
回答by david
Last day of the month
本月的最后一天
now = new Date
lastDayOfTheMonth = new Date(1900+now.getYear(), now.getMonth()+1, 0)
回答by Sajin M Aboobakkar
var month = 1; // 1 for January
var d = new Date(2015, month, 0);
console.log(d); // last day in January
回答by Nicolas Giszpenc
Sometimes all you have is a text version of the current month, ie: April 2017.
有时,您所拥有的只是当前月份的文本版本,即:2017 年 4 月。
//first and last of the current month
var current_month = "April 2017";
var arrMonth = current_month.split(" ");
var first_day = new Date(arrMonth[0] + " 1 " + arrMonth[1]);
//even though I already have the values, I'm using date functions to get year and month
//because month is zero-based
var last_day = new Date(first_day.getFullYear(), first_day.getMonth() + 1, 0, 23, 59, 59);
//use moment,js to format
var start = moment(first_day).format("YYYY-MM-DD");
var end = moment(last_day).format("YYYY-MM-DD");
回答by Infomaster
Do not forget month started with 0 so +1 in month too.
不要忘记月份以 0 开头,因此月份也是 +1。
let enddayofmonth = new Date(year, month, 0).getDate();
回答by yetAnotherSE
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));
Date lastDayOfMonth = cal.getTime();

