/**
* 计算两个时间中所有的月份
* @param date1 开始时间
* @param date2 结束时间
* @return
* @throws ParseException
*/
public static List<String> getMonths(String date1, String date2) throws ParseException{
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Date parse = sdf.parse(date1);
Date parse2 = sdf.parse(date2);
List<String> dateList = new ArrayList<>();
Calendar c1=Calendar.getInstance();
c1.setTime(parse);
//转为周一
int year = c1.get(Calendar.YEAR);
int month = c1.get(Calendar.MONTH);
c1.set(year, month, 1, 0, 0, 0);
Calendar c2=Calendar.getInstance();
c2.setTime(parse2);
int weekYear2 = c2.get(Calendar.YEAR);
int weekOfYear2 = c2.get(Calendar.WEEK_OF_YEAR);
c2.setWeekDate(weekYear2, weekOfYear2, Calendar.SUNDAY);
while (true) {
int tempMonth = c1.get(Calendar.MONTH);
String date = c1.getWeekYear() + "-" + ((tempMonth + 1) <= 9 ? "0" + (tempMonth + 1) : tempMonth + 1);
System.out.println(date);
dateList.add(date);
//下一个月<结束日期
c1.set(Calendar.MONTH, tempMonth +1);
if(c1.getTimeInMillis()>=c2.getTimeInMillis()){
break;
}
}
return dateList;
}
/**
* 计算两个时间内 所有的周数
* @param date1
* @param date2
* @return
* @throws ParseException
*/
public static List<String> getWeeks(String date1, String date2) throws ParseException{
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Date parse = sdf.parse(date1);
Date parse2 = sdf.parse(date2);
List<String> dateList = new ArrayList<>();
Calendar c1=Calendar.getInstance();
c1.setTime(parse);
//转为周一
int weekYear = c1.get(Calendar.YEAR);
int weekOfYear = c1.get(Calendar.WEEK_OF_YEAR);
c1.setWeekDate(weekYear, weekOfYear, Calendar.MONDAY);
Calendar c2=Calendar.getInstance();
c2.setTime(parse2);
int weekYear2 = c2.get(Calendar.YEAR);
int weekOfYear2 = c2.get(Calendar.WEEK_OF_YEAR);
c2.setWeekDate(weekYear2, weekOfYear2, Calendar.SUNDAY);
while (true) {
int weekNum = c1.get(Calendar.WEEK_OF_YEAR);
System.out.println(sdf.format(c1.getTime())+" : "+weekNum);
dateList.add(c1.getWeekYear() + "-" + (weekNum > 9 ? weekNum : "0" + weekNum));
if (c1.getTimeInMillis() >= c2.getTimeInMillis()) {
break;
}
//增加7天
c1.setTimeInMillis(c1.getTimeInMillis()+1000*60*60*24*7);
}
return dateList;
}
/**
* 计算两个时间内所有日期
* @param date1
* @param date2
* @return
* @throws ParseException
*/
public static List<String> getDays(String date1, String date2) throws ParseException{
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Long startTime = sdf.parse(date1).getTime();
Long endTime = sdf.parse(date2).getTime();
List<String> dateList = new ArrayList<String>();
Long oneDay = 1000 * 60 * 60 * 24l;
Long time = startTime;
while (time <= endTime) {
Date d = new Date(time);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String date=df.format(d);
System.out.println(date);
dateList.add(date);
time += oneDay;
}
return dateList;
}
效果展示:
1,生成连续的日期:(年-月-日)
2,生成连续的月份(年-月)
3,生成连续的周数(年-周数)