如何检查日期格式是否正确

时间:2019-04-22 11:27:16

标签: java datetime

我无法编写一种方法来测试日期的格式是否正确。

我编写了一种检查日期格式是否正确的方法,但是它给出了错误的结果,而且我找不到错误。

    boolean isDateFormatCorrect(String date) {
        LocalDate ld = null;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
        ld = LocalDate.parse(date, formatter);
        String result = ld.format(formatter);
        return result.equals(date);
    }
    @ParameterizedTest
    @CsvSource({"2019-04-20", "2017-01-13"})
    void isDateFormatCorrect(String date) {
        assertThat(currencyService
                .isDateFormatCorrect(date))
                .isEqualTo(true);
    }
    @ParameterizedTest
    @CsvSource({"20-04-2019", "01-01-1999", "22/2/2012", "2012/2/12"})
    void isDateFormatNotCorrect(String date) {
        assertThat(currencyService
                .isDateFormatCorrect(date))
                .isEqualTo(false);
    }

第一次测试提供正确答案,而第二次测试提供例外:

java.time.format.DateTimeParseException: Text '20-04-2019' could not be parsed at index 0

我相信答案很简单,但是我已经解决了一个多小时,但我已经失去了主意。

1 个答案:

答案 0 :(得分:0)

Use this one.

new DateTimeFormatterBuilder()
            .appendValue(ChronoField.YEAR, 4, 4, SignStyle.NEVER)
            .appendPattern("MMdd")
            .toFormatter()
            .withResolverStyle(ResolverStyle.STRICT)

Just to let you know the reason for exception is the invalid date component. Otherwise it is still a valid. For ex: 04-04-04 with yyyy-MM-dd is interpreted as 4th April 2004.

And this is Javadoc for DatetimeFormatter上以解析年份时,如何消除延迟。另请参见ResolverStyle

  

年份:字母的数量确定了最小字段宽度,在该最小字段宽度以下使用填充。如果字母数为2,则使用简化的两位数形式。对于打印,这将输出最右边的两位数字。对于解析,将使用2000的基值进行解析,从而得出2000到2099(含)之间的一年。如果字母数少于四个(但不是两个),则按照SignStyle.NORMAL,仅负数年输出符号。否则,按照SignStyle.EXCEEDS_PAD,如果超出焊盘宽度,则输出符号。

相关问题