Date and Time API in Java
Java 8 introduced the java.time package as a complete replacement for the old java.util.Date and java.util.Calendar classes, which were notoriously difficu...
Modern Date Handling with java.time
Java 8 introduced the java.time package as a complete replacement for the old java.util.Date and java.util.Calendar classes, which were notoriously difficult to use correctly. The new API was inspired by the Joda-Time library and is built on sound design principles: all core objects are immutable and thread-safe, the API is clearly named with consistent method prefixes, and time zones are handled explicitly rather than hidden.
Core Classes in java.time LocalDate represents a date without time or time zone: year, month, and day. LocalTime represents a time without a date or time zone: hour, minute, second, and nanosecond. LocalDateTime combines both. ZonedDateTime adds a time zone. Instant represents a point on the UTC timeline as seconds plus nanoseconds since the Unix epoch, making it ideal for timestamps stored in databases or sent over networks. Duration measures time between two instants, and Period measures the gap between two dates in human-friendly years, months, and days.
Creating and Manipulating Date-Time Objects All classes use static factory methods. LocalDate.now() returns today. LocalDate.of(2024, 3, 15) creates a specific date. Because the objects are immutable, modification methods like plusDays(7) and minusMonths(2) return new objects rather than changing the original. This makes date arithmetic safe and easy to reason about.
Formatting and Parsing DateTimeFormatter handles conversion between date-time objects and strings. You can use predefined formatters like DateTimeFormatter.ISO_LOCAL_DATE or define custom patterns with DateTimeFormatter.ofPattern("dd/MM/yyyy"). Call format(formatter) on a date-time object to get a string, and call LocalDate.parse(str, formatter) to convert a string back to a date.
Code Example: LocalDate today = LocalDate.now(); LocalDate nextWeek = today.plusDays(7); DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd-MM-yyyy"); System.out.println(today.format(fmt)); // e.g. 16-06-2026 System.out.println(nextWeek.format(fmt)); // e.g. 23-06-2026
Period gap = Period.between(today, nextWeek); System.out.println(gap.getDays()); // 7
Interview Tip: Interviewers commonly ask why java.util.Date was replaced. Key answers: Date is mutable and therefore not thread-safe; months are zero-indexed causing constant off-by-one errors; there is no clean separation between date-only, time-only, and date-time concepts. Knowing these pain points and naming the java.time replacements demonstrates solid Java knowledge.