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();
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
