// 近3个月
function getLast3Month() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth() + 1;//0-11表示1-12月
var day = now.getDate();
var dateObj = {};
dateObj.now = year + '-' + month + '-' + day;
var nowMonthDay = new Date(year, month, 0).getDate(); //当前月的总天数
if(month - 3 <= 0){ //如果是1、2、3月,年数往前推一年
var last3MonthDay = new Date((year - 1), (12 - (3 - parseInt(month))), 0).getDate(); //3个月前所在月的总天数
if(last3MonthDay < day){ //3个月前所在月的总天数小于现在的天日期
dateObj.last = (year - 1) + '-' + (12 - (3 - month)) + '-' + last3MonthDay;
}else{
dateObj.last = (year - 1) + '-' + (12 - (3 - month)) + '-' + day;
}
}else{
var last3MonthDay = new Date(year, (parseInt(month) - 3), 0).getDate(); //3个月前所在月的总天数
if(last3MonthDay < day){ //3个月前所在月的总天数小于现在的天日期
if(day < nowMonthDay){ //当前天日期小于当前月总天数,2月份比较特殊的月份
dateObj.last = year + '-' + (month - 3) + '-' + (last3MonthDay - (nowMonthDay - day));
}else{
dateObj.last = year + '-' + (month - 3) + '-' + last3MonthDay;
}
}else{
dateObj.last = year + '-' + (month - 3) + '-' + day;
}
}
return dateObj;
}
// 近一个月
function getLastMonth() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth() + 1;//0-11表示1-12月
var day = now.getDate();
var dateObj = {};
dateObj.now = year + '-' + month + '-' + day;
var nowMonthDay = new Date(year, month, 0).getDate(); //当前月的总天数
if(month - 1 <= 0){ //如果是1月,年数往前推一年<br>
dateObj.last = (year - 1) + '-' + 12 + '-' + day;
}else{
var lastMonthDay = new Date(year, (parseInt(month) - 1), 0).getDate();
if(lastMonthDay < day){ //1个月前所在月的总天数小于现在的天日期
if(day < nowMonthDay){ //当前天日期小于当前月总天数
dateObj.last = year + '-' + (month - 1) + '-' + (lastMonthDay - (nowMonthDay - day));
}else{
dateObj.last = year + '-' + (month - 1) + '-' + lastMonthDay;
}
}else{
dateObj.last = year + '-' + (month - 1) + '-' + day;
}
}
return dateObj;
}
// 近一周
function getLastWeek() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth() + 1;//0-11表示1-12月
var day = now.getDate();
var dateObj = {};
dateObj.now = year + '-' + month + '-' + day;
if(day - 7 <= 0){ //如果在当月7日之前
var lastMonthDay = new Date(year, (parseInt(month) - 1), 0).getDate(); //1周前所在月的总天数
if(month - 1 <= 0){ //如果在当年的1月份
dateObj.last = (year - 1) + '-' + 12 + '-' + (31 - (7 - day));
}else{
dateObj.last = year + '-' + (month - 1) + '-' + (lastMonthDay - (7 - day));
}
}else{
dateObj.last = year + '-' + month + '-' + (day -7);
}
return dateObj;
}
javaScript截取一周 、一个月、三个月的时间范围
最新推荐文章于 2024-04-29 03:12:34 发布