我有一个Java程序.在我的Java程序中,输入将是不同格式的日期字符串,如下所示
a) 2021-10-09T08:00:01.111Z ( with millisecond)
b) 2021-10-09T08:00:01Z ( without milliseconds)
c) 2021-10-09T08:00Z ( no seconds )
d) 2021-10-09T08Z ( no minutes )
目前,我使用的是内置的日期格式化程序DateTimeFormatter.ISO_OFFSET_DATE_TIME.但是,当我运行我的样例代码片段程序时,它失败了
以下是我的示 routine 序
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
public class Tester2 {
public static void main(String[] args) {
OffsetDateTime t1 = OffsetDateTime.parse("2021-10-09T08:00:01.111Z");;
System.out.println(t1.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
OffsetDateTime t2 = OffsetDateTime.parse("2021-10-09T08:00:01Z");;
System.out.println(t2.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
OffsetDateTime t3 = OffsetDateTime.parse("2021-10-09T08:00Z");;
System.out.println(t3.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
OffsetDateTime t4 = OffsetDateTime.parse("2021-10-09T08Z");;
System.out.println(t4.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
}
}
然而,当我运行我的程序时,它失败了,输出如下.
2021-10-09T08:00:01.111Z
2021-10-09T08:00:01Z
2021-10-09T08:00:00Z
Exception in thread "main" java.time.format.DateTimeParseException: Text '2021-10-09T08Z' could not be parsed at index 13
at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2052)
at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1954)
at java.base/java.time.OffsetDateTime.parse(OffsetDateTime.java:404)
at java.base/java.time.OffsetDateTime.parse(OffsetDateTime.java:389)
at test.Tester2.main(Tester2.java:20)
以下是我想要的输出
2021-10-09T08:00:01.111Z
2021-10-09T08:00:01Z
2021-10-09T08:00:00Z
2021-10-09T08:00:00Z
有没有什么Java内置的数据格式化程序可以帮助我实现想要的输出.如果没有这样的日期格式化程序,你能帮我写一个新的日期格式化程序吗?欢迎另一种解决方案.