How to check validity of Date String?

前端 未结 4 879
无人及你
无人及你 2020-12-04 01:16

In my project I need to check if a date string evaluates to a proper Date object. I\'ve decided to allow yyyy-MM-dd, and Date formats [(year, month, date) and (year, month,

4条回答
  •  天命终不由人
    2020-12-04 01:54

    For anyone popping by in 2017 or later, here is the Java 8 solution:

    private static DateTimeFormatter[] possibleFormats = {
        DateTimeFormatter.ofPattern("uuuu-MM-dd").withResolverStyle(ResolverStyle.STRICT),
        DateTimeFormatter.ofPattern("uuuu,MM,dd").withResolverStyle(ResolverStyle.STRICT),
        DateTimeFormatter.ofPattern("uuuu,MM,dd,HH,mm").withResolverStyle(ResolverStyle.STRICT),
        DateTimeFormatter.ofPattern("uuuu,MM,dd,HH,mm,ss").withResolverStyle(ResolverStyle.STRICT)
    };
    
    public Optional parseDate(String date) {
        for (DateTimeFormatter format : possibleFormats) {
            try {
                LocalDate result = LocalDate.parse(date, format);
                return Optional.of(result);
            } catch (DateTimeParseException dtpe) {
                // ignore, try next format
            }
        }
        return Optional.empty();
    }
    

    With DateTimeFormatter you can safely let the array of formatters be static even in a multithreaded environment: unlike SimpleDateFormat, a DateTimeFormatter is thread safe.

    A LocalDate is a date without a time, so if any hours and minutes were present in the string, they are lost. To get the hours, minutes and seconds out too you need a LocalDateTime, and then you need some trickery to make the parsing work in the cases where there are no hours and minutes in the string. You may either try both LocalDate.parse() and LocalDateTime.parse(), or you may build a formatter that has a default for hours to use when not in the string. DateTimeFormatterBuilder can do that.

提交回复
热议问题