首页 > 编程语言 > 详细

Java 日期验证和获取

时间:2021-09-15 23:14:28      阅读:55      评论:0      收藏:0      [点我收藏+]
 /**
     * 日期格式 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);
    }

 

Java 日期验证和获取

原文:https://www.cnblogs.com/ZJ199012/p/15268431.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!