本文为博主原创,转载请注明出处
public static Map<String,String> getMonthMap(int month){ Map<String,String> monthMap = new HashMap<>(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); // 获取前月的第一天 Calendar cal_1 = Calendar.getInstance();// 获取当前日期 cal_1.add(Calendar.MONTH, -month); cal_1.set(Calendar.DAY_OF_MONTH, 1);// 设置为1号,当前日期既为本月第一天 String firstDay = format.format(cal_1.getTime()); // 获取前月的最后一天 Calendar cale = Calendar.getInstance(); cale.add(Calendar.MONTH, -(month-1)); cale.set(Calendar.DAY_OF_MONTH, 0); String lastDay = format.format(cale.getTime()); monthMap.put("firstDay", firstDay); monthMap.put("lastDay", lastDay); return monthMap; }
---获取两个日期之间相差的月份:
public static List<String> getMonthBetween(String start, String end) { List<String> result = new ArrayList<>(); try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Calendar min = Calendar.getInstance(); Calendar max = Calendar.getInstance(); min.setTime(sdf.parse(start)); min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1); max.setTime(sdf.parse(end)); 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); } } catch (Exception e) { LOGGER.error(e.getMessage(), e); } return result; }