获取两个日期间月份
/** * 获取两个日期间月份 * @param minDate 开始日期 * @param maxDate 结束日期 * @return * @throws ParseException */ 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; } /** * 获取指定年月的最后一天 * @param yearMonth yyyy-MM * @return */ public static String getLastDayOfMonth(String yearMonth) { int year = Integer.parseInt(yearMonth.split("-")[0]); //年 int month = Integer.parseInt(yearMonth.split("-")[1]); //月 Calendar cal = Calendar.getInstance(); // 设置年份 cal.set(Calendar.YEAR, year); // 设置月份 // cal.set(Calendar.MONTH, month - 1); cal.set(Calendar.MONTH, month); //设置当前月的上一个月 // 获取某月最大天数 //int lastDay = cal.getActualMaximum(Calendar.DATE); int lastDay = cal.getMinimum(Calendar.DATE); //获取月份中的最小值,即第一天 // 设置日历中月份的最大天数 //cal.set(Calendar.DAY_OF_MONTH, lastDay); cal.set(Calendar.DAY_OF_MONTH, lastDay - 1); //上月的第一天减去1就是当月的最后一天 // 格式化日期 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); return sdf.format(cal.getTime()); } /** * 推算时间 * @param yyyyMM * @param forward * @return */ public static Date forwardDate(String yyyyMM, int forward) { Date date = DateUtil.str2Date(yyyyMM, DATE_FORMAT_YYYY_MM); Calendar instance = Calendar.getInstance(); instance.setTime(date); instance.add(Calendar.MONTH, forward); return instance.getTime(); } /** * 获取当前月份的上一个月 * @return */ public static String getLastMonth(){ SimpleDateFormat sdfMonth = new SimpleDateFormat("yyyy-MM"); Calendar c = Calendar.getInstance(); c.setTime(new Date()); c.add(Calendar.MONTH, -1); Date m = c.getTime(); String month = sdfMonth.format(m); return month; } /** * 获取当前月份的上n个月 * @return */ public static String getLastMonth(int n){ SimpleDateFormat sdfMonth = new SimpleDateFormat("yyyy-MM"); Calendar c = Calendar.getInstance(); c.setTime(new Date()); c.add(Calendar.MONTH, -n); Date m = c.getTime(); String month = sdfMonth.format(m); return month; }