Java / Java 21 Interview Questions
What are the key classes in the java.time package and when do you use each?
The java.time package (Java 8, JSR 310) replaces the problematic java.util.Date and java.util.Calendar classes. All classes are immutable and thread-safe by design.
| Class | Represents | Example |
|---|---|---|
| LocalDate | Date without time or timezone | 2024-03-15 |
| LocalTime | Time without date or timezone | 14:30:00.000 |
| LocalDateTime | Date + time, no timezone | 2024-03-15T14:30:00 |
| ZonedDateTime | Date + time + timezone | 2024-03-15T14:30:00+05:30[Asia/Kolkata] |
| OffsetDateTime | Date + time + fixed UTC offset | 2024-03-15T14:30:00+05:30 |
| Instant | Moment on UTC timeline (nanosecond precision) | 2024-03-15T09:00:00Z |
| Duration | Amount of time in hours/minutes/seconds | PT2H30M |
| Period | Amount of time in years/months/days | P1Y2M3D |
| ZoneId | A time zone ID | "Europe/London" |
// LocalDate operations
LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(1990, Month.JUNE, 15);
LocalDate nextMonth = today.plusMonths(1);
long days = ChronoUnit.DAYS.between(birthday, today);
// ZonedDateTime — essential for cross-timezone work
ZonedDateTime nyNow = ZonedDateTime.now(ZoneId.of("America/New_York"));
ZonedDateTime tokyoNow = nyNow.withZoneSameInstant(ZoneId.of("Asia/Tokyo"));
// Instant — machine time, for logging and persistence
Instant start = Instant.now();
// ... do work ...
Duration elapsed = Duration.between(start, Instant.now());
System.out.println("Elapsed: " + elapsed.toMillis() + "ms");
// Formatting / parsing
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
String formatted = today.atTime(14, 30).format(fmt);
LocalDateTime parsed = LocalDateTime.parse("25/12/2024 09:00", fmt);
// Converting legacy Date to Instant
Instant i = new Date().toInstant();
LocalDate ld = i.atZone(ZoneId.systemDefault()).toLocalDate();
More Related questions...