Java 8+ Date Time API Interview Questions & Best Practices
Core Questions & Best Practices
Q1. What were the core flaws of the legacy Java Date-Time API (java.util.Date, Calendar, SimpleDateFormat)?
- Thread-Unsafety (Mutability):
java.util.DateandCalendarobjects are mutable.SimpleDateFormatmaintains internal state in a sharedCalendarfield, causing race conditions and output corruption when accessed concurrently.- Confusing Zero-Based Months: Months were 0-indexed (), causing off-by-one bugs.
- Confusing Semantics:
java.util.Daterepresents an instant in UTC, but itstoString()method formats output using the host JVM's default timezone, misleading developers into thinking it carries timezone state.
Q2. How does the Java 8+ java.time package resolve thread-safety issues?
All classes in
java.time(LocalDate,LocalTime,LocalDateTime,ZonedDateTime,Instant,Duration,Period) are immutable and value-based. Methods like.plusDays()or.withHour()return a new instance instead of modifying the target object.DateTimeFormatteris completely stateless, making all formatters thread-safe and reusable across concurrent application threads.
Q3. What is the difference between Instant and ZonedDateTime?
Instantrepresents a specific epoch timestamp on the timeline in UTC ( on Jan 1, 1970). It has no timezone or calendar concept and is used for machine timestamps, database persistence, and audit logging.ZonedDateTimecombines aLocalDateTimewith aZoneId(e.g.,America/New_York), accounting for Daylight Saving Time (DST) rules and UTC offsets.
Q4. How do you test time-dependent logic deterministically in Java without using System.currentTimeMillis()?
Inject an instance of
java.time.Clockinto your spring components (Clock.systemUTC()). In unit tests, inject a static, frozen time usingClock.fixed(Instant, ZoneId)orClock.offset(). This eliminates system-clock dependency during test execution.
// Production Dependency Injection
@Service
public class OrderService {
private final Clock clock;
public OrderService(Clock clock) { this.clock = clock; }
public boolean isDiscountActive(LocalDate expiryDate) {
return LocalDate.now(clock).isBefore(expiryDate);
}
}
// Unit Test Setup (Frozen Time)
Clock frozenClock = Clock.fixed(Instant.parse("2026-06-01T00:00:00Z"), ZoneId.of("UTC"));
OrderService service = new OrderService(frozenClock);
Q5. How does ZonedDateTime handle Daylight Saving Time (DST) transitions?
When a local time falls into a DST Gap (Spring Forward, where 02:00 jumps to 03:00),
ZonedDateTimeautomatically adjusts the local time forward by the gap duration. When a local time falls into an Overlap (Fall Back, where 02:00 repeats),ZonedDateTimedefaults to using the earlier pre-transition offset.
