You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将日期字符串转换为Java.util.OffsetDateTime?解决DateTimeParseException异常

解决OffsetDateTime解析日期字符串的异常问题

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 13:32:39