第一种方式:
/** * 获取两个日期之间的所有月份 (年月) * * @param startTime * @param endTime * @return:YYYY-MM */ public static List<String> getMonthBetweenDate(String startTime, String endTime){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM"); // 声明保存日期集合 List<String> list = new ArrayList<String>(); try { // 转化成日期类型 Date startDate = sdf.parse(startTime); Date endDate = sdf.parse(endTime); //用Calendar 进行日期比较判断 Calendar calendar = Calendar.getInstance(); while (startDate.getTime()<=endDate.getTime()){ // 把日期添加到集合 list.add(sdf.format(startDate)); // 设置日期 calendar.setTime(startDate); //把日期增加一天 calendar.add(Calendar.MONTH, 1); // 获取增加后的日期 startDate=calendar.getTime(); } } catch (ParseException e) { e.printStackTrace(); } return list; } public static void main(String[] args) throws ParseException { String startStr = "2021-02-26"; String endStr = "2022-03-09"; List<String> list = getMonthBetweenDate(startStr, endStr); System.out.println(list); }第二种方式:
package enToCh; import ja.text.ParseException;import ja.text.SimpleDateFormat;import ja.util.ArrayList;import ja.util.Calendar;import ja.util.List; public class Demo1 {public static List<String> getMonthBetween(String minDate, String maxDate) throws ParseException { ArrayList<String> result = new ArrayList<String>(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");//格式化为年月 Calendar min = Calendar.getInstance(); Calendar max = Calendar.getInstance(); min.setTime(sdf.parse(minDate)); min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1); max.setTime(sdf.parse(maxDate)); max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2); Calendar curr = min; while (curr.before(max)) { result.add(sdf.format(curr.getTime())); curr.add(Calendar.MONTH, 1); } min = null;max = null;curr = null; return result; }public static void main(String[] args) throws ParseException {String minDate = "2018-01";String maxDate = "2018-06";List<String> list = getMonthBetween(minDate, maxDate);for(String s : list){System.out.println(s);}}}
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。