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

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

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


当前回答

试试这个:

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

其他回答

这对我很有用。 将提供给定年份和月份的最后一天:

var d = new Date(2012,02,0);
var n = d.getDate();
alert(n);

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

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

我觉得这对我来说是最好的解决办法。让Date对象为您计算它。

var today = new Date();
var lastDayOfMonth = new Date(today.getFullYear(), today.getMonth()+1, 0);

将day参数设置为0表示比本月的第一天小一天,即上个月的最后一天。

试试这个:

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

我将使用一个中间日期与下个月的第一天,并返回前一天的日期:

int_d = new Date(2008, 11+1,1);
d = new Date(int_d - 1);