js 获取上月的开始日期,结束日期


 
 

 至于计算年,lastMnonthDate不错,直接用函数计算减一后的结果了。 想尝试各种结果的可以用 new Date(1998,02,01);类似这样直接赋值。

这个还挺奇怪的。不过应该是能用的。有点疑问,有时间测试一下。

var now = new Date(); //当前日期
var nowDay = now.getDate(); //当前日
var nowMonth = now.getMonth(); //当前月
var nowYear = now.getYear(); //当前年
//console.log(nowMonth);
nowYear += (nowYear < 2000) ? 1900 : 0; //
var lastMonthDate = new Date(); //上月日期
// console.log('lastMonthDate'+lastMonthDate)
lastMonthDate.setDate(1);   //变成这个月一号
lastMonthDate.setMonth(lastMonthDate.getMonth()-1);
var lastYear = lastMonthDate.getYear();
lastYear += (lastYear < 2000) ? 1900 : 0; //
// console.log('lastYear'+lastYear);
var lastMonth = lastMonthDate.getMonth();
//  console.log('lastmonth'+lastMonth);

function getToday() {
    var now = new Date();
    var day = ("0" + now.getDate()).slice(-2);
    //  console.log(day);
    var month = ("0" + (now.getMonth() + 1)).slice(-2);
    var today = now.getFullYear() + "-" + (month) + "-" + (day);
    return today;
}
//获得本月的开始日期
function getMonthStartDate(){
    var monthStartDate = new Date(nowYear, nowMonth, 1);
    return formatDate(monthStartDate);
}
//格式化日期:yyyy-MM-dd
function formatDate(date) {
    var myyear = date.getFullYear();
    var mymonth = date.getMonth()+1;
    var myweekday = date.getDate();

    if(mymonth < 10){
        mymonth = "0" + mymonth;
    }
    if(myweekday < 10){
        myweekday = "0" + myweekday;
    }
    return (myyear+"-"+mymonth + "-" + myweekday);
}
//获得上月开始时间
function getLastMonthStartDate(){
    var lastMonthStartDate = new Date(lastYear, lastMonth, 1);
    return formatDate(lastMonthStartDate);
}
//获得上月结束时间
function getLastMonthEndDate(){
    var lastMonthEndDate = new Date(lastYear, lastMonth, getMonthDays(lastMonth));
    return formatDate(lastMonthEndDate);
}
//获得某月的天数 可以
function getMonthDays(myMonth){
    var monthStartDate = new Date(nowYear, myMonth, 1);
    var monthEndDate = new Date(nowYear, myMonth + 1, 1);
    //   console.log('天数'+monthStartDate+'==='+ monthEndDate)
    var days = (monthEndDate - monthStartDate)/(1000 * 60 * 60 * 24);
    //  console.log('天数,数量:'+days);
    return days;
}


猜你喜欢

转载自blog.csdn.net/qq_21208843/article/details/80907895