public List csgg(String y1,String y2){ List<String> list = new ArrayList<String>(); try { //将输入月份转换成日期格式 Date startDate = new SimpleDateFormat("yyyy-MM").parse(y1); Date endDate = new SimpleDateFormat("yyyy-MM").parse(y2); Calendar calendar = Calendar.getInstance(); calendar.setTime(startDate); // 获取开始年份和开始月份 int startYear = calendar.get(Calendar.YEAR); int startMonth = calendar.get(Calendar.MONTH); // 获取结束年份和结束月份 calendar.setTime(endDate); int endYear = calendar.get(Calendar.YEAR); int endMonth = calendar.get(Calendar.MONTH); for (int i = startYear; i <= endYear; i++) { String date = ""; if (i == startYear) { // 如果是输入的开始年份 for (int j = startMonth; j < 12; j++) { //从输入的开始月份开始计算 if (j < 9) { date = i + "-0" + (j + 1); } else { date = i + "-" + (j + 1); } list.add(date); } } else if (i == endYear) { //如果是输入的结束年份 for (int j = 0; j <= endMonth; j++) { //以输入的结束月份截止 if (j < 9) { date = i + "-0" + (j + 1); } else { date = i + "-" + (j + 1); } list.add(date); } } else { //包含在如输入的开始月份和输入的结束月份之间 for (int j = 0; j < 12; j++) { if (j < 9) { date = i + "-0" + (j + 1); } else { date = i + "-" + (j + 1); } list.add(date); } } } } catch (Exception e) { e.printStackTrace(); } return list; }
java 获取两个日期之间的所有月份
最新推荐文章于 2023-04-04 17:49:16 发布