/** * 日期格式 yyyyMMdd */ private static final String DATEFORMAT = "([0-9]{4})(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])"; /** * * isDate 判断是否是有效的日期 * @param date 日期字符串 * @return 是否 */ public static boolean isDate(String date) { Pattern pattern = Pattern.compile(DATEFORMAT); Matcher matcher = pattern.matcher(date); if (matcher.matches()) { pattern = Pattern.compile(DATE); matcher = pattern.matcher(date); if (matcher.matches()) { int y = Integer.valueOf(matcher.group(1)); int m = Integer.valueOf(matcher.group(2)); int d = Integer.valueOf(matcher.group(3)); if (d > 28) { Calendar c = Calendar.getInstance(); c.set(y, m - 1, 1); // 每个月的最大天数 int lastDay = c.getActualMaximum(Calendar.DAY_OF_MONTH); return (lastDay >= d); } } return true; } return false; }
private static final String DATEFORMAT = "([0-9]{4})(0[1-9]|1[012])"; private static final String DATE = "(\\d{4})(\\d{2})"; /** * 返回月份最后一天 * * @param month 日期 yyyyMM * @param amount 增加月份 * @return String */ public static String addMonth(String month, int amount) { Date result = null; Pattern pattern = Pattern.compile(DATEFORMAT); Matcher matcher = pattern.matcher(month); if (matcher.matches()) { pattern = Pattern.compile(DATE); matcher = pattern.matcher(month); if (matcher.matches()) { int y = Integer.parseInt(matcher.group(1)); int m = Integer.parseInt(matcher.group(2)); Calendar c = Calendar.getInstance(); c.set(y, (m - 1 + amount), 1); // 每个月的最大天数 int lastDay = c.getActualMaximum(Calendar.DAY_OF_MONTH); c.set(Calendar.DAY_OF_MONTH, lastDay); result = c.getTime(); } } SimpleDateFormat sdfDay = new SimpleDateFormat("yyyyMMdd"); return sdfDay.format(result); }