Tech Interview RoomStudy guides

Java 8

Java 8: Date and time problems with java.time (age, business days, time zones). Compare legacy and modern solutions.

Intermediate · 2 min read · Lesson 7 of 10 in Java 8

Problem

  1. Compute a person's age in years from their birth date.
  2. Count business days (Monday to Friday) between two dates.
  3. Convert a meeting at 10:00 in Mumbai to New York time on a given date.

Approach 1: Legacy Date and Calendar (what not to do)

Mutable, months start at 0, not thread-safe (SimpleDateFormat especially), and time zones are easy to get wrong.

java
import java.util.Calendar;
import java.util.GregorianCalendar;

class AgeLegacy {
    static int age(int year, int monthZeroBased, int day, Calendar today) {
        Calendar birth = new GregorianCalendar(year, monthZeroBased, day);   // month 0 = January!
        int age = today.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
        birth.add(Calendar.YEAR, age);                                        // mutates birth
        if (birth.after(today)) age--;
        return age;
    }
}

Approach 2: java.time Period and ChronoUnit (Java 8)

Immutable, thread-safe, ISO calendar with sensible month numbers. Period.between gives years, months and days; ChronoUnit counts a single unit.

java
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;

class AgeModern {
    static int age(LocalDate birth, LocalDate today) {
        return Period.between(birth, today).getYears();
    }
    static long daysUntilBirthday(LocalDate birth, LocalDate today) {
        LocalDate next = birth.withYear(today.getYear());
        if (next.isBefore(today) || next.isEqual(today)) next = next.plusYears(1);
        return ChronoUnit.DAYS.between(today, next);
    }
}

Approach 3: Business days three ways (loop, stream, O(1) arithmetic)

java
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

class BusinessDays {
    static boolean weekday(LocalDate d) {
        return d.getDayOfWeek() != DayOfWeek.SATURDAY && d.getDayOfWeek() != DayOfWeek.SUNDAY;
    }

    // 1. Loop day by day: O(days). Fine for short ranges.
    static long loop(LocalDate start, LocalDate endExclusive) {
        long count = 0;
        for (LocalDate d = start; d.isBefore(endExclusive); d = d.plusDays(1)) if (weekday(d)) count++;
        return count;
    }

    // 2. Stream (Java 9 datesUntil): O(days), declarative; easy to add a holiday filter.
    static long stream(LocalDate start, LocalDate endExclusive, java.util.Set<LocalDate> holidays) {
        return start.datesUntil(endExclusive).filter(BusinessDays::weekday).filter(d -> !holidays.contains(d)).count();
    }

    // 3. Arithmetic: O(1). Whole weeks contribute 5 days each; at most 6 leftover days are checked.
    static long formula(LocalDate start, LocalDate endExclusive) {
        long days = ChronoUnit.DAYS.between(start, endExclusive);
        long weeks = days / 7;
        long count = weeks * 5;
        for (LocalDate d = start.plusDays(weeks * 7); d.isBefore(endExclusive); d = d.plusDays(1)) if (weekday(d)) count++;
        return count;
    }
}

Approach 4: Time zones with ZonedDateTime (DST handled for you)

java
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

class MeetingTime {
    static final DateTimeFormatter FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm z");   // immutable, thread-safe

    static String convert(LocalDate date, LocalTime time, String fromZone, String toZone) {
        ZonedDateTime from = ZonedDateTime.of(date, time, ZoneId.of(fromZone));
        return from.withZoneSameInstant(ZoneId.of(toZone)).format(FMT);
    }
}

class DateDemo {
    public static void main(String[] args) {
        LocalDate today = LocalDate.of(2026, 11, 1), birth = LocalDate.of(1990, 11, 2);
        System.out.println(AgeLegacy.age(1990, 10, 2, new java.util.GregorianCalendar(2026, 10, 1)) + " " + AgeModern.age(birth, today)); // 35 35
        System.out.println(AgeModern.daysUntilBirthday(birth, today));                  // 1
        LocalDate s = LocalDate.of(2026, 11, 2), e = LocalDate.of(2026, 12, 1);
        System.out.println(BusinessDays.loop(s, e) + " " + BusinessDays.formula(s, e) + " "
            + BusinessDays.stream(s, e, java.util.Collections.singleton(LocalDate.of(2026, 11, 26))));   // 21 21 20
        System.out.println(MeetingTime.convert(LocalDate.of(2026, 11, 3), java.time.LocalTime.of(10, 0), "Asia/Kolkata", "America/New_York"));
    }
}

Which type to use

  • LocalDate / LocalTime / LocalDateTime: no zone, for birthdays, business dates, opening hours.
  • Instant: a point on the UTC timeline, for timestamps stored in databases and logs.
  • ZonedDateTime: a local time in a named zone with DST rules, for scheduling and display.
  • OffsetDateTime: a fixed offset, common in APIs and JSON.
  • Duration (seconds and nanos) vs Period (years, months, days).

Feasible → optimal

Legacy Calendar works but is error-prone. java.time is correct by construction. For business days, the loop and stream are O(days) and easy to extend with holidays; the arithmetic version is O(1) and best for very long ranges.

Follow-up questions interviewers ask

Try answering each one before you open it.

Why is SimpleDateFormat dangerous in a web application?

It keeps parsing state in instance fields, so sharing one instance (for example as a static field) between request threads corrupts results or throws random exceptions. The fixes were per-thread instances (ThreadLocal) or synchronisation; the real fix is DateTimeFormatter, which is immutable and thread-safe.

How should timestamps be stored and transferred?

Store instants in UTC (Instant, or TIMESTAMP WITH TIME ZONE in PostgreSQL), transfer them as ISO-8601 strings with an offset (2026-11-01T09:30:00Z), and convert to the user's zone only for display. Store the user's zone id (Asia/Kolkata) separately when you need to schedule future local events, because offsets change with DST and politics.