Java 8 个可选时间部分不起作用

Java 8 optional time part not working

我正在尝试为可选时间部分创建日期时间格式,目前我实现了这个

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.text.ParseException;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.println(Ideone.getDate("2017-07-01T00:00:00.0Z"));
        System.out.println(Ideone.getDate("2017-07-01T00:00:00.00Z"));
        System.out.println(Ideone.getDate("2017-07-01T00:00:00.000Z"));
    }
    
    public static LocalDateTime getDate(String date) {
        try {
           
            DateTimeFormatter formatter2 =
                DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss[.SSS]'Z'");
            LocalDateTime ldt = LocalDateTime.parse(date, formatter2);
            
            
            return ldt;
           
        } catch (DateTimeParseException ex) {
            return null;
        }
    }
}

并有输出

null

2017-07-01T00:00

2017-07-01T00:00

现在我的问题是,为什么时间分数为 1 的日期不起作用,而时间分数为 2 和 3 的日期却有效?它应该接受 1,2 和 3 分数吗?还是只有 3 个分数?

提前致谢

你在通过时得到 null 的原因是

"2017-07-01T00:00:00.0Z"

您已告诉解析器需要 3 个字符格式(见下文 .SSS

DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss[.SSS]'Z'");

如果您将其更改为 .SS,它应该可以工作,但是您的最后输入即 2017-07-01T00:00:00.000Z 会中断。您可能希望包含一些逻辑来处理不同的格式

我觉得你想要的是DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss[.SSS][.S]'Z'")

基本上是说首先检查 2+ 秒数的长格式,否则如果该可选字段不存在,请检查指定的单个秒数的可选字段通过 [.S]

这似乎是一个错误。日期时间解析的毫秒部分在 Java 8 中似乎存在一般错误,请参阅 this issue 及其副本。

相关引用:

Worse however is that the SSS pattern has therefore ended up using strict mode when lenient mode would be appropriate. As it currently stands, DateTimeFormatter.ofPattern("hhmmss.SSS") requires three digits for milliseconds, when it was originally intended to require 0 to 9 (the lenient behaviour).

Given that the current implementation requires three digits for SSS, it is thus very surprising that adjacent value parsing does not apply.

但是你好像发现了上面提到的要求也不适用的情况。此外,即使上述问题处于“已修复”状态,您的示例似乎在 both java 8 和 java 9:

>java -version
java version "9"
Java(TM) SE Runtime Environment (build 9+181)
Java HotSpot(TM) 64-Bit Server VM (build 9+181, mixed mode)

>javac Ideone.java

>java Ideone
null
2017-07-01T00:00
2017-07-01T00:00

>"c:\Program Files\Java\jdk1.8.0\bin"\javac Ideone.java

>"c:\Program Files\Java\jdk1.8.0\bin"\java Ideone
null
2017-07-01T00:00
2017-07-01T00:00

should it entertain 1,2 and 3 fractions? or only 3 fractions?

根据引用,它应该只有 3,虽然最初打算是 0-9。