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

标签 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);
    }

第一个测试提供了正确的答案,而第二个测试提供了一个异常(exception):

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

我相信答案很简单,但我已经尝试解决它一个多小时了,但我失去了想法。

最佳答案

使用这个。

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

只是让您知道异常的原因是无效的 date 组件。否则它仍然有效。例如:04-04-04yyyy-MM-dd 被解释为 2004 年 4 月 4 日。

这是 DatetimeFormatter 的 Javadoc用于解析年份。另请参阅ResolverStyle

Year: The count of letters determines the minimum field width below which padding is used. If the count of letters is two, then a reduced two digit form is used. For printing, this outputs the rightmost two digits. For parsing, this will parse using the base value of 2000, resulting in a year within the range 2000 to 2099 inclusive. If the count of letters is less than four (but not two), then the sign is only output for negative years as per SignStyle.NORMAL. Otherwise, the sign is output if the pad width is exceeded, as per SignStyle.EXCEEDS_PAD.

关于java - 如何检查日期格式是否正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55793646/

相关文章:

c# - 为什么减去两个本地 DateTime 值似乎不能解释夏令时?

java - Hibernate c3p0配置没有影响

java - 如何在Java中调用带参数的祖 parent 构造函数?

java - Android Java 库双向兼容

r - 如何绘制独立于日期的 POSIXct 对象/时间戳?

java - 如何在日期中添加一天?

java - TreeMap 获取第一个元素并移除

java - 如何使用 jdk 11 读取堆状态?

python - 在日期时间解析中使用当前月份/日期

php - 如何在 PHP 中 DST 切换前的最后一小时内从 DateTime 对象检索 unix 时间戳?