簡體   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))

示例:

> LastDayOfMonth(2009, 11)
Mon Nov 30 2009 23:59:59 GMT+0100 (CET)

這會給你當月的最后一天。

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

下面是上面代碼的輸出:
2013 年 10 月 3 日星期四 11:34:59 GMT+0100(GMT 夏令時)
2013 年 11 月 3 日星期日 11:34:59 GMT+0000(GMT 標准時間)
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   

本月的最后一天

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

有時,您所擁有的只是當前月份的文本版本,即: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