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

标签 java java-8 datetime-format java-time

我正在尝试为当前实现的可选时间部分创建日期时间格式

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 个分数?

提前致谢

最佳答案

这似乎是一个错误。日期时间解析的毫秒部分似乎是 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.

但是您似乎发现了上述要求也不适用的情况。此外,即使上述问题处于“已修复”状态,您的示例似乎在 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。

关于Java 8 可选时间部分不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46321529/

相关文章:

java - Android Java 应用程序安装

java - 如何使用 Files.walk()... 根据条件获取文件图?

javascript - DateTimePicker 值与显示日期不一致

javascript - 向格式为 'h:i:s: A' 的字符串添加分钟和秒的最快方法

java - 如何在 Java DateTime API 中使用 🎌 日本数字解析日期字符串

java - 来自应用程序类的 NoClassDefFound

java - 为什么 putHashmap 不按顺序显示数据?

java - java swing中定时器与for循环之间的性能?

java - 在 Windows XP 上安装 JDK8 - advapi32.dll 错误

java - 在 Java 中实现接口(interface)实例列表的通用容器