Java Notes
Complete guide to java.time package — LocalDate, LocalTime, LocalDateTime, ZonedDateTime, Duration, Period, formatting, parsing, and migration from legacy Date/Calendar.
Why a New Date/Time API?
The old java.util.Date and java.util.Calendar classes were fundamentally broken:
| Problem | Old API | New API (java.time) |
|---|---|---|
| Mutability | Date is mutable (thread-unsafe) | All classes are immutable |
| Month indexing | January = 0 | January = 1 |
| Year | 1900-based | Actual year |
| Timezone handling | Poor | First-class ZonedDateTime |
| Design | Confusing, inconsistent | Clean, fluent, ISO-8601 |
// Old API problems
Date date = new Date(2024, 1, 15); // Actually March 15, 3924!
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, 1); // February (0-indexed)!
// Mutable — another thread could change it
// New API — clean and intuitive
LocalDate date = LocalDate.of(2024, 1, 15); // January 15, 2024
LocalDate date2 = LocalDate.of(2024, Month.JANUARY, 15); // Same, more readableLocalTime — Time Without Date
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
LocalDateTime — Date + Time Without Timezone
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
ZonedDateTime — Full Date/Time with Timezone
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Duration and Period
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Formatting and Parsing
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Migration from Legacy API
// Date <-> Instant <-> LocalDateTime
Date legacyDate = new Date();
Instant instant = legacyDate.toInstant();
LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
// Back to Date
Date backToDate = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());
// Calendar <-> ZonedDateTime
Calendar calendar = Calendar.getInstance();
ZonedDateTime zdt = ZonedDateTime.ofInstant(calendar.toInstant(),
calendar.getTimeZone().toZoneId());
// java.sql.Date <-> LocalDate
java.sql.Date sqlDate = java.sql.Date.valueOf(LocalDate.now());
LocalDate localDate = sqlDate.toLocalDate();
// java.sql.Timestamp <-> LocalDateTime
java.sql.Timestamp timestamp = java.sql.Timestamp.valueOf(LocalDateTime.now());
LocalDateTime fromTimestamp = timestamp.toLocalDateTime();Real-World Examples
Interview Questions
Q1: Why is the new Date/Time API better than Date and Calendar?
Answer: Immutability (thread-safe), proper month indexing (1-12), separation of concerns (LocalDate vs LocalTime vs ZonedDateTime), fluent API, built-in timezone support, and ISO-8601 compliance.
Q2: What is the difference between LocalDateTime and ZonedDateTime?
Answer: LocalDateTime has no timezone info — it represents a date-time on a wall clock. ZonedDateTime includes timezone rules and can handle DST transitions. Use LocalDateTime for local events, ZonedDateTime for global timestamps.
Q3: What is the difference between Duration and Period?
Answer: Duration is time-based (hours, minutes, seconds) used with LocalTime/LocalDateTime. Period is date-based (years, months, days) used with LocalDate. "3 hours" is Duration; "2 months and 5 days" is Period.
Q4: How do you convert between old Date and new LocalDateTime?
Answer: Date.toInstant() → LocalDateTime.ofInstant(instant, zoneId) and back: LocalDateTime.atZone(zoneId).toInstant() → Date.from(instant).
Q5: What happens at DST boundaries with ZonedDateTime?
Answer: Java handles gaps (spring forward) by moving forward to the next valid time, and overlaps (fall back) by choosing the earlier offset by default. You can use withEarlierOffsetAtOverlap() or withLaterOffsetAtOverlap().
Q6: What is Instant and when should you use it?
Answer: Instant represents a specific moment on the UTC timeline (machine time). Use it for timestamps, measuring elapsed time, database storage, and any time you need an absolute point in time regardless of timezone.
Summary
In this chapter, we learned about Date and Time API in Java 8 in detail. Here are the key points:
- Basic introduction to the concept and why it is needed
- Syntax and structure with complete examples
- Internal working and best practices
- Real-world applications and use cases
- Common mistakes and how to avoid them
- How this topic is asked in interviews
To practice these concepts, write and run the code in your IDE and verify the output. Modify each example and experiment so that you deeply understand the concept.
Continue the lesson path