集合里包含月份: 开始~结束
2019-01-01 00:00:00
2019-01-31 23:59:00
2019-02-01 00:00:00
2019-02-28 23:59:00
2019-03-01 00:00:00
2019-03-31 23:59:00
public static void main(String[] args) throws ParseException {
long l = System.currentTimeMillis();//当前时间戳
String nowDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(l));//当前时间字符串
String startDate ="2019-01-01 00:00:00";
List<String> dates = findMonths(startDate, nowDate);
for (int i = 0; i < dates.size(); i++) {
System.out.println(dates.get(i));
}
}
/**
* 获取对应日期列表
* @param dBegin
* @param dEnd
* @return
* @throws ParseException
* @throws java.text.ParseException
*/
public static List<String> findMonths(String dBegin, String dEnd) throws ParseException, java.text.ParseException {
//日期工具类准备
DateFormat resulfmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//设置开始时间
Calendar calBegin = Calendar.getInstance();
calBegin.setTime(resulfmt.parse(dBegin));
//设置结束时间
Calendar calEnd = Calendar.getInstance();
calEnd.setTime(resulfmt.parse(dEnd));
//装返回的日期集合容器
List<String> dateList = new ArrayList<String>();
// 每次循环给calBegin日期加一天,直到calBegin.getTime()时间等于dEnd
while (calEnd.after(calBegin)) {
// 根据日历的规则,为给定的日历字段添加或减去指定的时间量
// 优先记录当月时间: 开始时间
dateList.add(resulfmt.format(calBegin.getTime()));
// 优先记录当月时间: 结束
// 当前日历月份加1 来到了下个月
calBegin.add(Calendar.MONTH, 1);
// 下个月天数减1 来到了当月(即开始月份)的最后一天
//calBegin.add(Calendar.DAY_OF_MONTH, -1);
// 下个月时间减1分钟 来到了当月(即开始月份)的最后一天的23:59:00
calBegin.add(Calendar.MINUTE,-1);
// 记录当月的结束时间 82800000L
dateList.add(resulfmt.format(calBegin.getTime()));//获取当前日历时间戳并格式化
// 当前月份加1得到下个月份
// calBegin.add(Calendar.DAY_OF_MONTH, 1);
calBegin.add(Calendar.MINUTE, 1);
//依次循环并记录日期
}
return dateList;
}