如何将日期字符串转换为Java.util.OffsetDateTime?解决DateTimeParseException异常
Got it, let's break down why your code is throwing a DateTimeParseException and fix it step by step.
问题根源
The core issue here is that your date string 2020-06-01T13:46:45.641956 doesn't include any time zone offset information (like +08:00 for Beijing time or Z for UTC). But OffsetDateTime is designed to represent a date-time with an offset from UTC/GMT—so it requires that offset data to parse successfully.
解决方案
Here are a few ways to fix this, depending on your use case:
1. 指定默认时区偏移量(推荐)
If you know the date should be treated as belonging to a specific time zone (like UTC), you can build a formatter that adds a default offset when it's missing from the input string:
String ts = "2020-06-01T13:46:45.641956"; // Build a formatter with default UTC offset (offset seconds = 0) DateTimeFormatter fmt = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSS") .parseDefaulting(ChronoField.OFFSET_SECONDS, 0) // Set UTC as default .toFormatter(); OffsetDateTime date = OffsetDateTime.parse(ts, fmt); System.out.println(date); // Output: 2020-06-01T13:46:45.641956Z
If you need to use the system's default time zone instead of UTC, adjust the default offset like this:
ZoneOffset systemOffset = ZoneId.systemDefault().getRules().getOffset(Instant.now()); DateTimeFormatter fmt = new DateTimeFormatterBuilder() .appendPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSS") .parseDefaulting(ChronoField.OFFSET_SECONDS, systemOffset.getTotalSeconds()) .toFormatter();
2. 修改输入字符串,添加时区偏移
If you can modify the input string to include the offset, you can use a formatter that handles the offset directly. For example, add Z to indicate UTC:
String ts = "2020-06-01T13:46:45.641956Z"; DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSXXX"); OffsetDateTime date = OffsetDateTime.parse(ts, fmt); System.out.println(date);
3. 先解析为LocalDateTime,再转换为OffsetDateTime
If you don't have offset info but still need an OffsetDateTime, you can first parse the string into a LocalDateTime (which doesn't require an offset), then attach the offset you need:
String ts = "2020-06-01T13:46:45.641956"; DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSS"); // Parse to LocalDateTime first LocalDateTime localDateTime = LocalDateTime.parse(ts, fmt); // Attach your desired offset (e.g., UTC) OffsetDateTime date = localDateTime.atOffset(ZoneOffset.UTC); System.out.println(date);
内容的提问来源于stack exchange,提问作者Great Falcon

