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)但结果仍然相同。
将以下行写入日志:
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)
如您所见,仅当second和nano部分的值大于 时才包括它们0。