你好,我尝试使用DateTimeFormatter将字符串20110330174824917解析为OffsetDateTime,因此
public static void main(String[] args) {
// System.out.println(OffsetDateTime.parse("20110330174824917", DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")));
System.out.println(LocalDateTime.parse("20110330174824917", DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")));
}但我得到了
线程"main“java.time.format.DateTimeParseException中出现异常:无法分析文本”20110330174824917“,在java.time.LocalDateTime.parse(LocalDateTime.java:492)处的java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1952)处的java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)处的索引8处找到未分析的文本
嘿,伙计们,看起来这个问题和java 8 https://bugs.openjdk.java.net/browse/JDK-8031085有关。
感谢大家的帮助
发布于 2021-02-23 22:56:38
您的日期-时间字符串没有时区信息,因此,为了将其解析为OffsetDateTime,您需要显式传递时区信息。您可以使用DateTimeFormatter#withZone将日期-时间字符串解析为ZonedDateTime,您可以使用ZonedDateTime#toOffsetDateTime将其转换为OffsetDateTime。
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDateTime = "20110330174824917";
// Change the ZoneId as per your requirement e.g. ZoneId.of("Europe/London")
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS", Locale.ENGLISH)
.withZone(ZoneId.systemDefault());
OffsetDateTime odt = ZonedDateTime.parse(strDateTime, dtf)
.toOffsetDateTime();
System.out.println(odt);
}
}输出:
2011-03-30T17:48:24.917+01:00发布于 2021-02-23 22:46:20
您可以为格式化程序定义使用的Zone,并将输入字符串与正确的区域偏移连接在一起
// note the added Z at the end of the pattern for the offset
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSSZ").withZone(ZoneId.of("UTC"));
OffsetDateTime dateTime = OffsetDateTime.parse("20110330174824917" + "+0000", formatter);https://stackoverflow.com/questions/66334981
复制相似问题