无法转换日期字符串至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:
- First parse the string into a
LocalDate(a class designed to store just date information): - 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
DateTimeFormatteruses the patternyyyy-MM-dd, which doesn't match the input string that includes hours, minutes, and seconds. OffsetDateTimerequires 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
OffsetDateTimeorZonedDateTime, 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
相关产品推荐
相关产品推荐

