如何区分 LocalDateTime 中缺少“第二个字段”的情况

Pra*_*mar 5 time localtime date-parsing java-8 localdate

我得到了LocalDateTime从 . 创建的对象String。我想检查原始字符串是否有“秒”参数。我的两个输入是:

String a = "2016-06-22T10:01"; //not given
String b = "2016-06-22T10:01:00"; //not given

LocalDateTime dateA = LocalDateTime.parse(a, DateTimeFormatter.ISO_DATE_TIME);
LocalDateTime dateB = LocalDateTime.parse(b, DateTimeFormatter.ISO_DATE_TIME);
Run Code Online (Sandbox Code Playgroud)

问题是我给出的是dateAdateB,而不是ab

我尝试了各种方法,例如转换LocalDateTimeString并找到其长度。为此我使用了两种方法。

date.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME).length();
date.toString().length();
Run Code Online (Sandbox Code Playgroud)

dateA但第一种方法为和提供长度 19 ,而第二种方法为和dateB 提供长度 16 。dateAdateB

我无法找到任何方法来区分dateAdateB

Yur*_*kov 1

在 Java 8 DateTime API 中,日期可以用以下方式表示:

正如您所看到的,无法区分年-月-日-时-分-秒和年-月-日-时-分。String因此,从到 的转换LocalDateTime完成后 - 您无法区分它。执行此操作的唯一方法是使用String(通过长度或正则表达式),而不是使用LocalDateTime对象。