如何在java中将空字符串转换为LocalDate?

Jin*_*tin -5 java exception java-8

我需要将空字符串转换为 LocalDate 对象。我尝试使用

LocalDate.parse("");
Run Code Online (Sandbox Code Playgroud)

但有一个例外说:

java.time.format.DateTimeParseException: Text '' could not be parsed at index 0
Run Code Online (Sandbox Code Playgroud)

有人可以帮我吗。

Vit*_*yuk 5

在这样的转换之后你期望得到什么?如果您需要当前时间,您应该使用:

LocalDate.now()
Run Code Online (Sandbox Code Playgroud)

迭代列表时 - 添加一条if语句来检查是否String为空/空,甚至检查它是否可以被解析 - 如果不能 - 处理它,例如返回 null/抛出异常/返回LocalDate.now()或执行您需要的任何其他操作。

如果您使用的是 java8 - 您可以过滤非空/空字符串,例如

list
.stream()
.filter(str-> str!=null && !str.isEmpty())
//and you can collect values to list if you need
.map(LocalDate::parse)
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)