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

无法转换日期字符串至ZoneDateTime及DateTimeParseException异常求助

Fixing Date Parsing Issues with ZonedDateTime and OffsetDateTime

Hey there, let's break down and fix these two date parsing problems you're facing:

Problem 1: Converting "2018-03-29" to ZonedDateTime

The string "2018-03-29" only holds a date component—no time or timezone details—but ZonedDateTime requires all three (date, time, and a valid timezone). Here's how to make the conversion work properly:

  1. First parse the string into a LocalDate (a class designed to store just date information):
  2. Add a default time (like midnight) and specify a timezone to get a complete ZonedDateTime.
String rejectedDateStr = "2018-03-29";
// Parse the raw date string to LocalDate
LocalDate localDate = LocalDate.parse(rejectedDateStr);

// Convert to ZonedDateTime using your system's default timezone at midnight
ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());

// Or use a specific timezone like UTC if your use case requires it
ZonedDateTime zonedDateTimeUtc = localDate.atStartOfDay(ZoneId.of("UTC"));

Problem 2: DateTimeParseException for "2018-03-29 16:15:30"

Your error pops up for two critical reasons:

  • Your DateTimeFormatter uses the pattern yyyy-MM-dd, which doesn't match the input string that includes hours, minutes, and seconds.
  • OffsetDateTime requires a timezone offset (like +08:00), which your input string doesn't provide.

Here's the corrected code:

String dateStr = "2018-03-29 16:15:30";
// Use a formatter pattern that exactly matches the full datetime string
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

// First parse to LocalDateTime (handles datetime without timezone/offset)
LocalDateTime localDateTime = LocalDateTime.parse(dateStr, fmt);

// Convert to OffsetDateTime by explicitly specifying an offset (e.g., UTC)
OffsetDateTime offsetDateTime = localDateTime.atOffset(ZoneOffset.UTC);

// Alternatively, use your system's default timezone offset
OffsetDateTime offsetDateTimeLocal = localDateTime.atOffset(
    ZoneId.systemDefault().getRules().getOffset(localDateTime)
);

// Proceed with your predicate logic as before
predicates.add(cb.equal(root.get(entry.getKey()), offsetDateTime));

Quick Reminders:

  • Always double-check that your formatter pattern perfectly aligns with the structure of your input string.
  • When working with OffsetDateTime or ZonedDateTime, never skip specifying a timezone/offset if your input doesn't include one—explicitly define it based on your application's needs.

内容的提问来源于stack exchange,提问作者vivek pandey

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:05:33