如何在java中将空字符串转换为LocalDate? [英] How to convert empty string to a LocalDate in java?

查看:1756
本文介绍了如何在java中将空字符串转换为LocalDate?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to convert an empty string to a LocalDate object. I tried using

LocalDate.parse("");

但有例外说:

java.time.format.DateTimeParseException: Text '' could not be parsed at index 0

有人可以帮助我。

推荐答案

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

What do you expect to get after such converting? In case you need current time you should use:

LocalDate.now()

迭代列表时 - 添加 if 语句来检查 String in not null / empty甚至检查是否可以解析 - 如果没有 - 处理它,例如return null / throw exception / return LocalDate.now( )或做你需要的任何其他行动。

When iterating list - add an if statement to check that String in not null/empty or even check whether it could be parsed - and if no - handle it, for example return null/throw exception/return LocalDate.now() or do any other action you need.

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

If you are using java8 - you can filter not empty/null Strings like

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

这篇关于如何在java中将空字符串转换为LocalDate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆