我得到了从String
创建的对象LocalDateTime
。我想检查原始字符串是否具有"秒"参数。我的两个输入是:
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);
问题是我得到了dateA
和dateB
,而不是a
和b
。
我尝试了各种方法,例如将LocalDateTime
转换为String
并找到其长度。为此,我使用了两种方法。
date.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME).length();
date.toString().length();
但是第一种方法为dateA
和dateB
提供长度 19,而第二种方法为dateA
和dateB
提供长度 16。
我找不到任何方法来区分dateA
和dateB
.
正如其他人已经说过的,LocalDateTime
对象总是有第二部分。另一个问题是原始输入是否有第二部分。仅用Java-8-means就可以找到答案(但它很丑陋,因为它基于异常控制流(:
String a = "2016-06-22T10:01"; // not given
String b = "2016-06-22T10:01:00"; // given
boolean hasSecondPart;
try {
TemporalAccessor tacc =
DateTimeFormatter.ISO_DATE_TIME.parseUnresolved(a, new ParsePosition(0));
tacc.get(ChronoField.SECOND_OF_MINUTE);
hasSecondPart = true;
} catch (UnsupportedTemporalTypeException ex) {
hasSecondPart = false;
}
System.out.println(hasSecondPart); // true for input b, false for input a
旁注:
使用以下代码,我的库 Time4J 可以无异常地检查字符串输入是否有第二部分:
boolean hasSecondPart =
Iso8601Format.EXTENDED_DATE_TIME.parseRaw(a).contains(PlainTime.SECOND_OF_MINUTE);
在 ISO_DATE_TIME
中,秒是可选的(如果不存在,则设置为零(,这就是它解析两个输入的原因。并且LocalDateTime.toString()
方法仅在秒不为零时才打印秒。
因此,一旦创建了LocalDateTime
对象,就无法知道原始String
是否具有秒字段。
要验证输入String
中是否存在秒字段,您必须创建自己的模式并检查它在解析时是否引发异常:
// formatter with required seconds
DateTimeFormatter withSecs = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
LocalDateTime.parse(b, withSecs); // OK
LocalDateTime.parse(a, withSecs); // DateTimeParseException
如果你只想检查字段是否存在,但不想构建一个LocalDateTime
对象,你也可以使用 parseUnresolved
方法,它不会引发异常:
ParsePosition position = new ParsePosition(0);
withSecs.parseUnresolved(a, position);
if(position.getErrorIndex() == -1) {
System.out.println("No error (it contains seconds)"); // b gets here
} else {
System.out.println("Error (it does not contain seconds)"); // a gets here
}
In Java 8 DateTime API 日期可以通过以下方式表示:
- 本地日期作为年-月-日
- 本地日期时间为年-月-日-小时-分钟-秒
- ZonedDateTime as年-月-日-小时-分钟-秒与时区
秒和年-月-日-小时-分钟。因此,从String
转换为LocalDateTime
完成后 - 您无法区分它。执行此操作的唯一方法是使用 String
(按长度或正则表达式(,而不是使用LocalDateTime
对象。