js获取指定日期所在月的第一天和最后一天

//获取指定日期所在月的第一天和最后一天
function getfirstDateAndlastDate(){
    var dateStr = "2021-02-16 09:36:39";
    var date = new Date(dateStr);
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    if(month > 12){
        month = 1;
        year++;
    }
    if (month < 10) {
        month = '0' + month
    }
    var monthLastDay = new Date(year, month, 0).getDate();
    var firstDate = year + '-' + month + '-' + '01';
    var lastDate = year + '-' + month + '-' + monthLastDay;
    console.log(firstDate);
    console.log(lastDate);
}
//使用moment.js
//获取指定日期所在月的第一天
var firstDate = moment("2022-02").startOf("month").format("YYYY-MM-DD");
//获取指定日期所在月的第一天
var lastDate = moment("2022-02").endOf("month").format("YYYY-MM-DD");

 

posted @ 2022-02-17 16:15  一隅桥畔  阅读(3133)  评论(0)    收藏  举报