如何区分本地日期时间中缺少"second field"



我得到了从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);

问题是我得到了dateAdateB,而不是ab

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

date.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME).length();
date.toString().length();

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

我找不到任何方法来区分dateAdateB.

正如其他人已经说过的,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对象。

最新更新