我有这段代码可以将字符串双向解析为 LocalDateTime:
public class ConvertLocalDateToString {
private static final DateTimeFormatter CUSTOM_LOCAL_DATE;
static {
CUSTOM_LOCAL_DATE = new DateTimeFormatterBuilder()
.appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
.appendLiteral('-')
.appendValue(MONTH_OF_YEAR, 2)
.appendLiteral('-')
.appendValue(DAY_OF_MONTH, 2)
.appendLiteral(' ')
.appendValue(HOUR_OF_DAY, 2)
.appendLiteral(':')
.appendValue(MINUTE_OF_HOUR, 2)
.optionalStart()
.appendLiteral(':')
.appendValue(SECOND_OF_MINUTE, 2)
.toFormatter();
}
public static void main(String[] args) {
String str = "2020-02-18 15:04:30";
LocalDateTime dateTime = LocalDateTime.parse(str, CUSTOM_LOCAL_DATE); //2020-02-18T15:04:30
LocalDateTime addedDateTime = LocalDateTime.parse(dateTime.plusHours(10).format(CUSTOM_LOCAL_DATE.withZone(ZoneOffset.UTC)));
System.out.println(addedDateTime);
System.out.println(dateTime); //2020-02-18T15:04:30
}
我的假设是“T”字母是由 ISO-8601 格式自动生成的。这导致:
DateTimeParseException: Text '2020-02-18 15:04:30' could not be parsed at index 10
如何摆脱它?
最佳答案
System.out.println(dateTime)
与 System.out.println(String.valueOf(dateTime))
相同。
String.valueOf(dateTime)
与 dateTime.toString()
相同,只是它可以处理 null
值。
在 LocalDateTime
上调用 toString()
是 documented为此:
Outputs this date-time as a String, such as
2007-12-03T10:15:30
.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.
如果您需要不同的格式,请调用format(DateTimeFormatter formatter)
.
那么,回答你的问题:
My assumption is 'T' letter is auto-generated by ISO-8601 format.
T
并不比 -
和 :
字符更自动生成。
How do I get rid of it?
调用format(...)
并指定您想要的格式,例如
System.out.println(dateTime.format(DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss")));
关于java - 使用 DateTimeFormatterBuilder 将 String 解析为 LocalDateTime 时如何防止自动生成 'T' 字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60312178/