Java : DateTimeParseException with Examples
DateTimeParseException (Java SE 19 & JDK 19) API Examples.
You will find code examples on most DateTimeParseException methods.
Summary
System.out.println("-- OK --");
final var date1 = LocalDate.parse("2100-12-31");
System.out.println("date : " + date1);
System.out.println("-- NG --");
try {
final var date2 = LocalDate.parse("2100-12-40");
} catch (DateTimeParseException e) {
System.out.println("DateTimeParseException! : " + e.getMessage());
}
// Result
// ↓
//-- OK --
//date : 2100-12-31
//-- NG --
//DateTimeParseException! : Text '2100-12-40' could not be parsed:
// Invalid value for DayOfMonth (valid values 1 - 28/31): 40
Constructors
DateTimeParseException (String message, CharSequence parsedData, int errorIndex)
final var e = new DateTimeParseException("abcd", "2100-12-40", 8);
System.out.println(e); // java.time.DateTimeParseException: abcd
System.out.println(e.getMessage()); // abcd
System.out.println(e.getParsedString()); // 2100-12-40
System.out.println(e.getErrorIndex()); // 8
DateTimeParseException (String message, CharSequence parsedData, int errorIndex, Throwable cause)
final var cause = new DateTimeException("XYZ");
final var e = new DateTimeParseException("abcd", "2100-12-40", 8, cause);
System.out.println(e); // java.time.format.DateTimeParseException: abcd
System.out.println(e.getMessage()); // abcd
System.out.println(e.getParsedString()); // 2100-12-40
System.out.println(e.getErrorIndex()); // 8
System.out.println(e.getCause()); // java.time.DateTimeException: XYZ
System.out.println(e.getCause().getMessage()); // XYZ
Methods
int getErrorIndex ()
Please see DateTimeParseException(String message, CharSequence parsedData, int errorIndex).
String getParsedString ()
Please see DateTimeParseException(String message, CharSequence parsedData, int errorIndex).
Methods declared in Throwable
addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
Please see the link below.
Related posts
- Get the current time
- Basics of Date and Time
- Don't use the legacy Date and Calendar classes, use new APIs instead
- API Examples
- Calendar
- ChronoLocalDate
- Clock
- Date
- DateTimeException
- DayOfWeek
- Duration
- Era
- Instant
- InstantSource
- JapaneseDate
- LocalDate
- LocalDateTime
- LocalTime
- Month
- MonthDay
- OffsetDateTime
- OffsetTime
- Period
- Temporal
- TemporalAccessor
- TemporalAdjuster
- TemporalAdjusters
- TimeZone
- Year
- YearMonth
- ZonedDateTime
- ZoneId
- ZoneOffset