根据两个时间段,取这两个时间段内有多少个月份
/*
* 创建日期 2004-11-29
*
*
*/
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
/**
* @author wubai
*
*根据两个时间段,取这两个时间段内有多少个月份
*
*/
public class Test {
public String getMonthList(String beginDateStr, String endDateStr) {
//指定要解析的时间格式
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
//返回的月份列表
String sRet = "";
//定义一些变量
Date beginDate = null;
Date endDate = null;
GregorianCalendar beginGC = null;
GregorianCalendar endGC = null;
try {
//将字符串parse成日期
beginDate = f.parse(beginDateStr);
endDate = f.parse(endDateStr);
//设置日历
beginGC = new GregorianCalendar();
beginGC.setTime(beginDate);
endGC = new GregorianCalendar();
endGC.setTime(endDate);
//直到两个时间相同
while(beginGC.getTime().compareTo(endGC.getTime())<=0){
//累加字符串,用单引号分隔
if (sRet.equals("")) {
sRet += beginGC.get(Calendar.YEAR) + "-" + (beginGC.get(Calendar.MONTH)+1);
}
else {
sRet += "," + beginGC.get(Calendar.YEAR) + "-" + (beginGC.get(Calendar.MONTH)+1);
}
//以月为单位,增加时间
beginGC.add(Calendar.MONTH,1);
}
return sRet;
}
catch(Exception e) {
e.printStackTrace();
return null;
}
}
//测试用
public static void main(String[] args) {
Test test = new Test();
String tmp;
tmp = test.getMonthList("2004-03-09", "2004-08-10");
System.out.println("month list:" + tmp);
//返回结果如下:
//month list:2004-3,2004-4,2004-5,2004-6,2004-7,2004-8
//也就是说月份前没有加0补全,为了程序的简洁,所以没有加,可以自己补全
}
}