缺少 LocalDateTime.parse 中的第二个(00)

use*_*r84 1 java java-time localdatetime datetimeformatter

缺少第二个 (00) 从 LocalDateTime.parse

LocalTime time = LocalTime.NOON;
DateTimeFormatter formatTime = DateTimeFormatter.ofPattern("HH:mm:ss");
String value ="20200810" + time.format(formatTime);
LocalDateTime localDateTime = LocalDateTime.parse(value, DateTimeFormatter.ofPattern("yyyyMMddHH:mm:ss"));
Run Code Online (Sandbox Code Playgroud)

日志

LocalTime time = LocalTime.NOON;
DateTimeFormatter formatTime = DateTimeFormatter.ofPattern("HH:mm:ss");
String value ="20200810" + time.format(formatTime);
LocalDateTime localDateTime = LocalDateTime.parse(value, DateTimeFormatter.ofPattern("yyyyMMddHH:mm:ss"));
Run Code Online (Sandbox Code Playgroud)

我也尝试更改LocalTime.NOON为,LocalTime.of(12,0,0)但结果仍然相同。

Arv*_*ash 5

将以下行写入日志:

localDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
Run Code Online (Sandbox Code Playgroud)

上面的行按照 返回一个字符串DateTimeFormatter.ISO_LOCAL_DATE_TIME

您还可以根据您的要求指定自定义模式,例如

localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
Run Code Online (Sandbox Code Playgroud)

或者

localDateTime.format(DateTimeFormatter.ofPattern("yyyyMMddHH:mm:ss"))
Run Code Online (Sandbox Code Playgroud)

如果localDateTime直接打印,会打印出toString方法返回的字符串LocalDateTime

请注意,由于second时间中的部分12:00:00is 00, 的默认toString实现会LocalDateTime忽略该second部分。

供您参考,下面给出的是toString()实现LocalDateTime

@Override
public String toString() {
    return date.toString() + 'T' + time.toString();
}
Run Code Online (Sandbox Code Playgroud)

和下面给出toString()的实施LocalTime

@Override
public String toString() {
    StringBuilder buf = new StringBuilder(18);
    int hourValue = hour;
    int minuteValue = minute;
    int secondValue = second;
    int nanoValue = nano;
    buf.append(hourValue < 10 ? "0" : "").append(hourValue)
        .append(minuteValue < 10 ? ":0" : ":").append(minuteValue);
    if (secondValue > 0 || nanoValue > 0) {
        buf.append(secondValue < 10 ? ":0" : ":").append(secondValue);
        if (nanoValue > 0) {
            buf.append('.');
            if (nanoValue % 1000_000 == 0) {
                buf.append(Integer.toString((nanoValue / 1000_000) + 1000).substring(1));
            } else if (nanoValue % 1000 == 0) {
                buf.append(Integer.toString((nanoValue / 1000) + 1000_000).substring(1));
            } else {
                buf.append(Integer.toString((nanoValue) + 1000_000_000).substring(1));
            }
        }
    }
    return buf.toString();
}
Run Code Online (Sandbox Code Playgroud)

如您所见,仅当secondnano部分的值大于 时才包括它们0

  • @user84 您的 LocalDateTime 中没有丢失任何内容。它具有与您想要和期望它具有的完全相同的值。您的问题在于您用于日志输出的所述对象的字符串表示形式。如果您希望 LocalDateTime 对象的输出采用特定格式,那么您需要使用具有您想要的输出格式的格式化程序。 (3认同)