• Java8 时间字符串校验是否为对应的日期格式


    时间字符串格式校验

    严格模式下校验日期字符串

    public static boolean isDateStrict(String dateStr, String pattern) {
        try {
            DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                .appendPattern("yyyyMMdd")
                .parseDefaulting(ChronoField.ERA, 1)
                .toFormatter()
                .withChronology(IsoChronology.INSTANCE)
                .withResolverStyle(ResolverStyle.STRICT);
            LocalDate.parse(dateStr, formatter);
        } catch (Exception e) {
            log.error("时间格式不正确:{}", e.getMessage());
            return false;
        }
        return true;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    此方法可以严格校验 yyyyMMdd 的日期格式,或直接使用 uuuuMMdd 的形式转化:

    private static final DateTimeFormatter FORMAT = DateTimeFormatter.ofPattern("uuuuMMdd ")
                                        .withChronology(IsoChronology.INSTANCE)
                                        .withResolverStyle(STRICT);
    public static LocalDate parse(String dateStr) {
        return LocalDate.parse(dateStr, FORMAT);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    这是因为在 Java 8 的新日期 API 下,yyyy 表示公元纪年(year-era),这种格式在解析日期时会检查公元位(G),不存在时会报错;而 uuuu 表示和公元没有关系的年。上面例子中使用 parseDefaulting(ChronoField.ERA, 1) 设置一个默认的公元纪年位,表示公元后,就和我们正常的日期保持一致。

    严格模式下使用yyyy不指定纪元的报错:

    java.time.format.DateTimeParseException: Text ‘19820228’ could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {MonthOfYear=2, DayOfMonth=28, YearOfEra=1982},ISO of type java.time.format.Parse

    当然如果你使用非严格模式,yyyy 和 uuuu 在使用上没有区别。

    如果使用非严格模式的 DateTimeFormatter 可能并不会真正的检查出日期字符串的错误,比如 20230230,转日期类型并不会报错,会自动转成一个正确的日期 20230228;

    而使用 SimpleDateFormmat 也会有一些问题,比如 2023052,会转成 20230502。

    public static boolean isDateSimple(String dateStr, String pattern) {
        try {
            SimpleDateFormat format = new SimpleDateFormat(pattern);
            format.setLenient(false);
            format.parse(dateStr);
        } catch (Exception e) {
            log.error("时间格式不正确:{}", e.getMessage());
            return false;
        }
        return true;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    public static boolean isDateFormatter(String dateStr, String pattern) {
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
            LocalDate.parse(dateStr, formatter);
        } catch (Exception e) {
            log.error("时间格式不正确:{}", e.getMessage());
            return false;
        }
        return true;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    参考:https://stackoverflow.com/questions/26393594/using-new-java-8-datetimeformatter-to-do-strict-date-parsing

  • 相关阅读:
    selenium UI使用小技巧集合
    Celery笔记六之worker介绍
    高级版的 jvisualvm :Spring Boot Admin 监控 Spring Boot 微服务项目
    发个地区和对应的价格方案
    MMPretrain
    求解多目标多旅行商问题的非支配排序遗传算法(NSGA-II)
    用纯css实现一个图片拼接九宫格
    下个牛市来临时,哪些跨链应用有望成为新独角兽并值得提前布局?
    CentOS7安装MySQL8
    【数据结构】栈与队列
  • 原文地址:https://blog.csdn.net/Ep_Little_prince/article/details/134256596