js獲取近三個月、近一個月、近一週時間

獲取近一週時間

var end = new Date();
var year = end.getFullYear();
var month = end.getMonth() + 1;//0-11表示1-12月
var day = end.getDate();
var dateObj = {};
dateObj.end = year + '-' + month + '-' + day;
if (day - 7 <= 0) {   //若是在當月7日以前
    var startMonthDay = new Date(year, (parseInt(month) - 1), 0).getDate();    //1周前所在月的總天數
    if (month - 1 <= 0) { //若是在當年的1月份
      dateObj.start = (year - 1) + '-' + 12 + '-' + (31 - (7 - day));
    } else {
      dateObj.start = year + '-' + (month - 1) + '-' + (startMonthDay - (7 - day));
    }
} else {
    dateObj.start = year + '-' + month + '-' + (day - 7);
}
console.log(JSON.stringify(dateObj))

獲取近一個月時間

var end = new Date();
var year = end.getFullYear();
var month = end.getMonth() + 1;//0-11表示1-12月
var day = end.getDate();
var dateObj = {};
dateObj.end = year + '-' + month + '-' + day;
var endMonthDay = new Date(year, month, 0).getDate();    //當前月的總天數
if(month - 1 <= 0){ //若是是1月,年數往前推一年<br>    
    dateObj.start = (year - 1) + '-' + 12 + '-' + day;
}else{
    var startMonthDay = new Date(year, (parseInt(month) - 1), 0).getDate();
    if(startMonthDay < day){    //1個月前所在月的總天數小於如今的天日期
        if(day < endMonthDay){        //當前天日期小於當前月總天數
            dateObj.start = year + '-' + (month - 1) + '-' + (startMonthDay - (endMonthDay - day));
        }else{
            dateObj.start = year + '-' + (month - 1) + '-' + startMonthDay;
        }
    }else{
        dateObj.start = year + '-' + (month - 1) + '-' + day;
    }
}
console.log(JSON.stringify(dateObj))

獲取近三個月時間

var end = new Date();
var year = end.getFullYear();
var month = end.getMonth() + 1;//0-11表示1-12月
var day = end.getDate();
var dateObj = {};
dateObj.end = year + '-' + month + '-' + day;
var endMonthDay = new Date(year, month, 0).getDate();    //當前月的總天數
if(month - 3 <= 0){ //若是是一、二、3月,年數往前推一年
    var start3MonthDay = new Date((year - 1), (12 - (3 - parseInt(month))), 0).getDate();    //3個月前所在月的總天數
    if(start3MonthDay < day){    //3個月前所在月的總天數小於如今的天日期
        dateObj.start = (year - 1) + '-' + (12 - (3 - month)) + '-' + start3MonthDay;
    }else{
        dateObj.start = (year - 1) + '-' + (12 - (3 - month)) + '-' + day;
    }
}else{
    var start3MonthDay = new Date(year, (parseInt(month) - 3), 0).getDate();    //3個月前所在月的總天數
    if(start3MonthDay < day){    //3個月前所在月的總天數小於如今的天日期
        if(day < endMonthDay){        //當前天日期小於當前月總天數,2月份比較特殊的月份
            dateObj.start = year + '-' + (month - 3) + '-' + (start3MonthDay - (endMonthDay - day));
        }else{
            dateObj.start = year + '-' + (month - 3) + '-' + start3MonthDay;
        }
    }else{
        dateObj.start = year + '-' + (month - 3) + '-' + day;
    }
}
console.log(JSON.stringify(dateObj))
相關文章
相關標籤/搜索