如果在Date中提供0作为dayValue。setFullYear你会得到上个月的最后一天:

d = new Date(); d.setFullYear(2008, 11, 0); //  Sun Nov 30 2008

在mozilla中有这种行为的参考。这是一个可靠的跨浏览器功能吗?或者我应该看看其他的方法吗?


当前回答

我最近不得不做一些类似的事情,这是我想到的:

/**
* Returns a date set to the begining of the month
* 
* @param {Date} myDate 
* @returns {Date}
*/
function beginningOfMonth(myDate){    
  let date = new Date(myDate);
  date.setDate(1)
  date.setHours(0);
  date.setMinutes(0);
  date.setSeconds(0);   
  return date;     
}

/**
 * Returns a date set to the end of the month
 * 
 * @param {Date} myDate 
 * @returns {Date}
 */
function endOfMonth(myDate){
  let date = new Date(myDate);
  date.setDate(1); // Avoids edge cases on the 31st day of some months
  date.setMonth(date.getMonth() +1);
  date.setDate(0);
  date.setHours(23);
  date.setMinutes(59);
  date.setSeconds(59);
  return date;
}

向它传递一个日期,它将返回一个设置为月初或月底的日期。

begninngOfMonth函数是相当不言自明的,但是endOfMonth函数中的内容是,我将这个月递增到下个月,然后使用setDate(0)将前一天回滚到上个月的最后一天,这是setDate规范的一部分:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate https://www.w3schools.com/jsref/jsref_setdate.asp

然后我将小时/分/秒设置为一天的结束,这样如果您正在使用某种期望日期范围的API,您将能够捕获最后一天的全部内容。这部分内容可能超出了最初帖子的要求,但它可以帮助其他人寻找类似的解决方案。

编辑:如果您想要更加精确,还可以使用setMilliseconds()额外设置毫秒。

其他回答

试试这个。

lastDateofTheMonth = new Date(year, month, 0)

例子:

new Date(2012, 8, 0)

输出:

Date {Fri Aug 31 2012 00:00:00 GMT+0900 (Tokyo Standard Time)}

如果你只需要得到一个月的最后一个日期,下面的工作为我。

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

我知道这只是一个语义问题,但我最终以这种形式使用它。

var lastDay = new Date(new Date(2008, 11+1,1) - 1).getDate();
console.log(lastDay);

因为函数是从内部参数向外解析的,所以工作原理是一样的。

然后,您可以用所需的详细信息替换年和月/年,无论它来自当前日期。或者一个特定的月/年。

对我来说,这段代码很有用

end_date = new Date(2018, 3,1).toISOString().split('T')[0] console.log (end_date)

试试这个:

function _getEndOfMonth(time_stamp) {
    let time = new Date(time_stamp * 1000);
    let month = time.getMonth() + 1;
    let year = time.getFullYear();
    let day = time.getDate();
    switch (month) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            day = 31;
            break;
        case 4:
        case 6:
        case 9:
        case 11:
            day = 30;
            break;
        case 2:
            if (_leapyear(year))
                day = 29;
            else
                day = 28;
            break
    }
    let m = moment(`${year}-${month}-${day}`, 'YYYY-MM-DD')
    return m.unix() + constants.DAY - 1;
}

function _leapyear(year) {
    return (year % 100 === 0) ? (year % 400 === 0) : (year % 4 === 0);
}