很久很久以前···也就是前几天经理让我实现一个获取前十天、前十月、前十个季度的功能,百度一下没有结果,没办法自己写了一个,再此发到网上,希望广大同行能多多指点!
//声明时间
var myDate = new Date();
var endDate = new Date(myDate);
var day; //日
var month; //月
var year; //年
if(type == "ri") {
dateStr = "";
for(var i=0; i<10; i++) {
//如果当日时间差<1时,则获取前一个月的天数
if((myDate.getDate()-i) < 1) {
//获取前一个月的最后一天
endDate.setMonth(myDate.getMonth());
endDate.setDate(0);
//前月最后一天 + 相差天数(此天数是负数) = 实际应显示天数
day = ((endDate.getDate()+(myDate.getDate()-i))<10?"0":"")+(endDate.getDate()+(myDate.getDate()-i));
//如果获取月份为0,则取前一年的最后一个月
if(myDate.getMonth() == 0) {
month = 12;
year = myDate.getFullYear()-1;
} else {
month = ((myDate.getMonth())<10?"0":"")+(myDate.getMonth());
year = myDate.getFullYear();
}
} else {
day = ((myDate.getDate()-i)<10?"0":"")+(myDate.getDate()-i);
month = ((myDate.getMonth()+1)<10?"0":"")+(myDate.getMonth()+1);
year = myDate.getFullYear();
}
if(i > 0) {
dateStr += ",";
}
dateStr += year+"-"+month+"-"+day;
}
} else if(type == "yue") {
dateStr = "";
for(var i=0; i<10; i++) {
//获取当天
day = (myDate.getDate()<10?"0":"")+myDate.getDate();
//获取上一个月份
if((myDate.getMonth()+1-i) < 1) {
month = ((12+(myDate.getMonth()+1-i))<10?"0":"")+(12+(myDate.getMonth()+1-i));
year = myDate.getFullYear()-1;
} else {
month = ((myDate.getMonth()+1-i)<10?"0":"")+(myDate.getMonth()+1-i);
year = myDate.getFullYear();
}
if(i > 0) {
dateStr += ",";
}
dateStr += year+"-"+month+"-"+day;
}
} else if(type == "ji") {
dateStr = "";
for(var i=0; i<10; i++) {
day = (myDate.getDate()<10?"0":"")+myDate.getDate();
var season;
if((myDate.getMonth()+1) <= 3) {
month = "01";
year = myDate.getFullYear() + "";
myDate = new Date((myDate.getFullYear()-1)+"-12-"+day);
season = "1";
} else if((myDate.getMonth()+1) <= 6) {
month = "04";
year = myDate.getFullYear() + "";
myDate = new Date(year+"-03-"+day);
season = "2";
} else if((myDate.getMonth()+1) <= 9) {
month = "07";
year = myDate.getFullYear() + "";
myDate = new Date(year+"-06-"+day);
season = "3";
} else if((myDate.getMonth()+1) <= 12) {
month = "10";
year = myDate.getFullYear() + "";
myDate = new Date(year+"-09-"+day);
season = "4";
}
if(i > 0) {
dateStr += ",";
}
dateStr += year+"-"+month+"-"+day;
}
}
季度方面我为了方便获取的是每个季度的第一月也就是1、4、7、10月份,传给后台啊,还是干啥的处理在每个月的基础上加3就OK了