gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:25:08 30 4
gpt4 key购买 nike

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

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

    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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com