gpt4 book ai didi

Java 8 LocalDateTime 在使用 00 秒(如 "2018-07-06 00:00:00")解析日期字符串值时丢弃 00 秒值

转载 作者:搜寻专家 更新时间:2023-10-31 08:25:10 24 4
gpt4 key购买 nike

下面的代码 (Java 8) 片段删除了我的日期时间秒部分,当秒值在解析的日期内为时使用 LocalDateTime.parse,例如 2018-07-10 00:00:00:

final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
final LocalDateTime localDateTime = LocalDateTime.parse("2018-07-06 00:00:00", dateTimeFormatter);
final String lexicalDate = localDateTime.toString();
System.out.println("Lexical Date : "+ lexicalDate);
final XMLGregorianCalendar gregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(lexicalDate);
System.out.println("Gregorian Calendar : "+ gregorianCalendar);

词汇日期打印为:

Lexical Date : 2018-07-10T00:00

代替:

Lexical Date : 2018-07-10T00:00:00

现在这会影响公历的日期值,当秒被删除时返回 null。在秒值大于零的其他情况下,它工作得很好。

javax.xml.datatype.DatatypeFactory.newInstance().newXMLGregorianCalendar(lexicalDate)

只要秒值由于解析字符串中的 00 秒值而被删除,上面的代码就会返回 null。

有人可以协助使用 LocalDate 时间以更好的方式处理此问题,否则它可能是 Java 8 LocalDateTime 中的错误/有趣的控件。

请注意,我无法控制此日期值,它来自第三方平台。

最佳答案

特性,不是错误

您正在查看 LocalDateTime::toString 使用的特定 DateTimeFormatter 的记录行为方法。

摘录,我的重点:

The output will be one of the following ISO-8601 formats:

uuuu-MM-dd'T'HH:mm

uuuu-MM-dd'T'HH:mm:ss

uuuu-MM-dd'T'HH:mm:ss.SSS

uuuu-MM-dd'T'HH:mm:ss.SSSSSS

uuuu-MM-dd'T'HH:mm:ss.SSSSSSSSS

The format used will be the shortest that outputs the full value of the time where the omitted parts are implied to be zero.

如果你想在生成String的时候有其他行为来代表你的值LocalDateTime , 使用不同的 DateTimeFormatter并将其传递给 LocalDateTime::format .

String output = myLocalDateTime.format( someOtherFormatter ) ;

LocalDateTime 没有“格式”,因为它不是 文本。 DateTimeFormatter 的工作是解析或生成 String特定格式的对象。

关于Java 8 LocalDateTime 在使用 00 秒(如 "2018-07-06 00:00:00")解析日期字符串值时丢弃 00 秒值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50786482/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com