给一个开始时间和一个结束时间,求中间的连续时间(用java实现)?如:开始时间为140825,结束时间为140902,那连续时间为 140825,140826,140827,140828,140829,140830,140831,140901,140902
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
/**
*时间格式化工具类
*/
public class ChartDateFormatUtils {
/**
* 获取两个时间相差的天数
*
* @param date1
* @param date2
* @return
*/
public static int getBetweenDays(Date date1, Date date2) {
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
long time1 = cal.getTimeInMillis();
cal.setTime(date2);
long time2 = cal.getTimeInMillis();
long between_days = (time2 - time1) / (1000 * 3600 * 24);
return Integer.parseInt(String.valueOf(between_days));
}
/**
* 获取连续时间
*
* @param tempList
* @return
* @throws ParseException
*/
@SuppressWarnings("deprecation")
public static List<String> getContinuousTime(List<String> tempList) throws ParseException {
String startTime = tempList.get(0);
String endTime = tempList.get(tempList.size() - 1);
SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
Date startDate = sdf.parse(startTime);
Date endDate = sdf.parse(endTime);
int betweenDay = getBetweenDays(startDate, endDate) + 1;
Calendar curTime = new GregorianCalendar(startDate.getYear(), startDate.getMonth(), startDate.getDate());
SimpleDateFormat dateformat2 = new SimpleDateFormat("yyMMdd");
List<String> dataList = new ArrayList<String>();
for (int i = 1; i <= betweenDay; i++) {
String dateKey = dateformat2.format(curTime.getTime());
dataList.add(dateKey);
curTime.add(Calendar.DATE, 1);
}
return dataList;
}
public static void main(String[] args) {
List<String> tempList = new ArrayList<String>();
tempList.add("140715");
tempList.add("140717");
tempList.add("140817");
try {
for (String str : getContinuousTime(tempList)) {
System.out.println(str);
}
} catch (ParseException e) {
e.printStackTrace();
}
}
}