简体   繁体   English

如何获得本月的最后一天

[英]How to get last day of the month

如何获取时间戳为晚上 11:59:59 的月份的最后一天?

 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)

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));

 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) 2013 年 10 月 3 日星期四 11:34:59 GMT+0100(GMT 夏令时)
Sun Nov 03 2013 11:34:59 GMT+0000 (GMT Standard Time) 2013 年 11 月 3 日星期日 11:34:59 GMT+0000(GMT 标准时间)
Thu Oct 31 2013 11:34:59 GMT+0000 (GMT Standard Time) 2013 年 10 月 31 日星期四 11:34:59 GMT+0000(GMT 标准时间)

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   

Last day of the month本月的最后一天

now = new Date
lastDayOfTheMonth = new Date(1900+now.getYear(), now.getMonth()+1, 0)
var month = 1; // 1 for January
var d = new Date(2015, month, 0);
console.log(d); // last day in January

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");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));

Date lastDayOfMonth = cal.getTime();

不要忘记月份以 0 开头,因此月份也是 +1。

let enddayofmonth = new Date(year, month, 0).getDate();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM