gpt4 book ai didi

Java 8 LocalDateTime 正在解析无效日期

转载 作者:IT老高 更新时间:2023-10-28 20:50:08 28 4
gpt4 key购买 nike

我想在客户端验证日期,所以我编写了以下代码。但是,我没有得到异常,而是得到了 2 月 31 日日期字符串的正确日期对象,这显然是一个无效的日期。

public class Test {

public static void main(String[] args) {
String dateFormat = "HH:mm:ss MM/dd/yyyy";
String dateString = "11:30:59 02/31/2015";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(dateFormat, Locale.US);
try {
LocalDateTime date = LocalDateTime.parse(dateString, dateTimeFormatter);
System.out.println(date);
} catch (Exception e) {
// Throw invalid date message
}
}
}

输出:2015-02-28T11:30:59

有谁知道为什么 LocalDateTime 解析这个日期而不是抛出异常。

最佳答案

你只需要一个严格的 ResolverStyle .

Parsing a text string occurs in two phases. Phase 1 is a basic text parse according to the fields added to the builder. Phase 2 resolves the parsed field-value pairs into date and/or time objects. This style is used to control how phase 2, resolving, happens.

示例代码 - 其中 withResolverStyle(ResolverStyle.STRICT) 是重要的变化,同时使用 uuuu 而不是 yyyy(其中uuuu 是 "year"而 "yyyy"是 "year of era",因此不明确):

import java.time.*;
import java.time.format.*;
import java.util.*;

public class Test {

public static void main(String[] args) {
String dateFormat = "HH:mm:ss MM/dd/uuuu";
String dateString = "11:30:59 02/31/2015";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter
.ofPattern(dateFormat, Locale.US)
.withResolverStyle(ResolverStyle.STRICT);
try {
LocalDateTime date = LocalDateTime.parse(dateString, dateTimeFormatter);
System.out.println(date);
} catch (DateTimeParseException e) {
// Throw invalid date message
System.out.println("Exception was thrown");
}
}
}

关于Java 8 LocalDateTime 正在解析无效日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32823368/

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