LocalDateTime 重写了toString方法,在注释中说明了这种情况,当为0时会省略。
/**
* Outputs this time as a {@code String}, such as {@code 10:15}.
* <p>
* The output will be one of the following ISO-8601 formats:
* <ul>
* <li>{@code HH:mm}</li>
* <li>{@code HH:mm:ss}</li>
* <li>{@code HH:mm:ss.SSS}</li>
* <li>{@code HH:mm:ss.SSSSSS}</li>
* <li>{@code HH:mm:ss.SSSSSSSSS}</li>
* </ul>
* The format used will be the shortest that outputs the full value of
* the time where the omitted parts are implied to be zero.
*
* @return a string representation of this time, not null
*/
@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();
}
解决的办法:
String UTC_FORMATTER_PATTERN = "yyyy-MM-dd'T'HH:mm:ss";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(UTC_FORMATTER_PATTERN);
System.out.println(dateTimeFormatter.format(LocalDateTime.parse("2022-01-01T00:00:00")));
版权声明:本文为YISHENGYOUNI95原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。