一、前三个月:可根据传入数组的长度及for循环设置i的长度及last3Months[x-i],x的值来传入获取几个月
/**
* 获取前三个月
* @return 包含当前月的前三个月度
* @author Administrator
*/
public static String[] getLast3Months() {
String[] last3Months = new String[3];
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) + 1);
// 要先+1,才能把本月的算进去
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
//格式化可自行定义
Date date = new Date();
for (int i = 0; i < 3; i++) {
cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 1);
// 逐次往前推1个月
date = cal.getTime();
String st = sdf.format(date);
last3Months[2 - i] = st;
}
return last3Months;
}
二、上一个月:可根据(Calendar.Month,-x),传入的x来获取获取过去第几个月
/**
* 获取上一个月(如:201506)
* @return 得到上个月月度
* @author Administrator
*/
public String getLastDate() {
Calendar cal = Calendar.getInstance();
cal.get(Calendar.YEAR);
cal.add(Calendar.MONTH, -1);// 月份减1
Date date = cal.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
//格式化可自行定义
month = sdf.format(date);
return month;
}