Date and Time API Questions
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Date and time questions are easy to get wrong under pressure: months, time zones and "age from a birth date". The interviewer checks that you know why java.time replaced Date, which class fits which job, and the classic traps.
Why java.time replaced Date and Calendar
java.time is the modern date and time package from Java 8. Its classes are immutable and thread-safe, months start at 1, and there are separate types for a date, a date-time, a zoned date-time and an instant.
The old Date and Calendar classes caused real bugs. This example shows three of them next to the java.time version.
Example 1 · Old API traps vs java.time
import java.time.LocalDate;import java.util.Calendar;import java.util.Date;import java.util.GregorianCalendar;
public class OldVsNewDemo { public static void main(String[] args) { // Old API: months start at 0, so 1 means FEBRUARY Calendar cal = new GregorianCalendar(2026, 1, 15); System.out.println("Calendar month field for '1': " + cal.get(Calendar.MONTH) + " (that is February)");
// Old API: Date is mutable, anyone holding it can change it Date examDate = new Date(1_000_000_000_000L); Date sameObject = examDate; sameObject.setTime(0L); System.out.println("examDate millis after someone else's change: " + examDate.getTime());
// New API: months start at 1, objects are immutable LocalDate exam = LocalDate.of(2026, 2, 15); LocalDate moved = exam.plusDays(3); System.out.println("java.time exam: " + exam + ", moved copy: " + moved); System.out.println("Month: " + exam.getMonth() + " (" + exam.getMonthValue() + ")"); }}Calendar month field for '1': 1 (that is February) examDate millis after someone else's change: 0 java.time exam: 2026-02-15, moved copy: 2026-02-18 Month: FEBRUARY (2)
What this code does
new GregorianCalendar(2026, 1, 15)is 15 February, becauseCalendarmonths start at 0.LocalDate.of(2026, 2, 15)says February with a 2.- Changing the
Datethrough a second reference changed the original too.exam.plusDays(3)returns a newLocalDateand leavesexamuntouched.
Model answer, spoken: "java.time fixed these: its classes are immutable and thread-safe, months start at 1, there are separate types for a date, a date-time, a zoned date-time and an instant, and DateTimeFormatter is thread-safe. It is based on the Joda-Time library." Revise: Legacy Date and Calendar (opens in a new tab).
Must know:
java.util.Dateis mutable, its name lies (it holds a moment, not a date) and many methods are deprecated.Calendarnumbers months from 0, so1means February;SimpleDateFormatis not thread-safe.- New =
LocalDate,LocalTime,LocalDateTime,ZonedDateTime,Instant,Period,Duration,DateTimeFormatter. - Bridges:
date.toInstant(),Date.from(instant)for old libraries;ZoneIdreplacesTimeZone.
Find the bug
Spot the old-API trap
Each snippet has a classic old-API bug. Tap the wrong line, then check the fix.
Set the exam date to 15 March 2026.
Round 1 of 3LocalDate, LocalDateTime, ZonedDateTime, Instant: when to use each
Instant is a single point on the UTC timeline, counted from 1970-01-01T00:00Z (the epoch). Use it for timestamps, such as when a payment happened or a createdAt column.
The same moment looks different in each type. This example prints a local time, a zoned time and an instant for one flight.
Example 2 · Local, zoned and instant types side by side
import java.time.Instant;import java.time.LocalDate;import java.time.LocalDateTime;import java.time.LocalTime;import java.time.ZoneId;import java.time.ZonedDateTime;
public class TypesDemo { public static void main(String[] args) { LocalDate birthday = LocalDate.of(2005, 8, 15); LocalTime classStart = LocalTime.of(9, 30); LocalDateTime departure = LocalDateTime.of(2026, 1, 20, 9, 30); System.out.println("LocalDate: " + birthday); System.out.println("LocalTime: " + classStart); System.out.println("LocalDateTime: " + departure);
ZonedDateTime inIndia = departure.atZone(ZoneId.of("Asia/Kolkata")); ZonedDateTime inLondon = inIndia.withZoneSameInstant(ZoneId.of("Europe/London")); System.out.println("ZonedDateTime: " + inIndia); System.out.println("Same instant: " + inLondon);
Instant instant = inIndia.toInstant(); System.out.println("Instant (UTC): " + instant); System.out.println("Epoch seconds: " + instant.getEpochSecond()); }}LocalDate: 2005-08-15 LocalTime: 09:30 LocalDateTime: 2026-01-20T09:30 ZonedDateTime: 2026-01-20T09:30+05:30[Asia/Kolkata] Same instant: 2026-01-20T04:00Z[Europe/London] Instant (UTC): 2026-01-20T04:00:00Z Epoch seconds: 1768881600
What this code does
- The three
Localtypes print with no zone.atZone(Asia/Kolkata)turns the departure into a real moment (+05:30), andwithZoneSameInstantshows the same moment in London: 04:00 in January (UTC+0). toInstant()gives the UTC point on the timeline, which is the value to store;getEpochSecond()is the number of seconds since 1970-01-01T00:00Z.
LocalDate is a date with no time and no zone (a birthday, an exam date), LocalTime is a time of day, and LocalDateTime is a date and time with no zone (a departure printed on a ticket). ZonedDateTime adds a zone such as Asia/Kolkata, so it is a real moment. Model answer: "Store moments as Instant (UTC); convert to ZonedDateTime only to show them to a user in their zone." Revise: Instant and time zones (opens in a new tab) and LocalTime and LocalDateTime (opens in a new tab).
Must know:
LocalXtypes have no zone, so they cannot tell which moment they mean.ZoneId.of("Asia/Kolkata")is IST, UTC+05:30, with no daylight saving.withZoneSameInstantconverts a moment to another zone;withZoneSameLocalkeeps the clock time and changes the moment.OffsetDateTimehas a fixed offset like+05:30without zone rules; common in databases and JSON.
Predict the output
Which time is it?
Read each program and pick what it prints.
Round 1 of 4
21:40 in India, shown in London (summer time, UTC+1).
Period vs Duration, and DateTimeFormatter
Period is an amount of time in years, months and days, used with dates, for example P3Y10M11D. Duration is an amount in hours, minutes and seconds, used with times, for example PT7H30M.
Use Period for "how old" and Duration for "how long did the train take". This example also formats and parses a date.
Example 3 · Period for dates, Duration for times
import java.time.Duration;import java.time.LocalDate;import java.time.LocalDateTime;import java.time.Period;
public class PeriodDurationDemo { public static void main(String[] args) { LocalDate admission = LocalDate.of(2023, 7, 20); LocalDate graduation = LocalDate.of(2027, 5, 31); Period course = Period.between(admission, graduation); System.out.println("Period: " + course); System.out.println("In words: " + course.getYears() + " years, " + course.getMonths() + " months, " + course.getDays() + " days");
LocalDateTime depart = LocalDateTime.of(2026, 3, 10, 22, 45); LocalDateTime arrive = LocalDateTime.of(2026, 3, 11, 6, 15); Duration journey = Duration.between(depart, arrive); System.out.println("Duration: " + journey); System.out.println("In words: " + journey.toHours() + " h " + journey.toMinutesPart() + " min");
System.out.println("Period.ofDays(1) on a date: " + admission.plus(Period.ofDays(1))); System.out.println("Duration.ofHours(30) on a time: " + depart.plus(Duration.ofHours(30))); }}Period: P3Y10M11D In words: 3 years, 10 months, 11 days Duration: PT7H30M In words: 7 h 30 min Period.ofDays(1) on a date: 2023-07-21 Duration.ofHours(30) on a time: 2026-03-12T04:45
What this code does
Period.betweengives years, months and days (P3Y10M11D) for a course length.Duration.betweengives an exact time amount (PT7H30M) for an overnight train.toMinutesPart()(Java 9) gives the minutes left after whole hours. AddingDuration.ofHours(30)to a date-time moves it across a date boundary correctly.
Example 4 · Formatting, parsing and the MM vs mm trap
import java.time.LocalDate;import java.time.LocalDateTime;import java.time.format.DateTimeFormatter;import java.time.format.DateTimeParseException;
public class FormatParseDemo { public static void main(String[] args) { DateTimeFormatter indian = DateTimeFormatter.ofPattern("dd-MM-yyyy"); DateTimeFormatter ticket = DateTimeFormatter.ofPattern("dd MMM yyyy, hh:mm a");
LocalDate result = LocalDate.parse("05-06-2026", indian); System.out.println("Parsed: " + result); System.out.println("ISO: " + LocalDate.parse("2026-06-05")); System.out.println("Format: " + result.format(indian));
LocalDateTime train = LocalDateTime.of(2026, 6, 5, 21, 40); System.out.println("Ticket: " + train.format(ticket.withLocale(java.util.Locale.ENGLISH)));
DateTimeFormatter wrong = DateTimeFormatter.ofPattern("dd-mm-yyyy"); // mm = minutes System.out.println("mm trap: " + train.format(wrong));
try { LocalDate.parse("2026/06/05"); } catch (DateTimeParseException e) { System.out.println("Error: " + e.getMessage()); } }}Parsed: 2026-06-05 ISO: 2026-06-05 Format: 05-06-2026 Ticket: 05 Jun 2026, 09:40 PM mm trap: 05-40-2026 Error: Text '2026/06/05' could not be parsed at index 4
What this code does
- One formatter parses
05-06-2026as 5 June (day first) and formats it back.LocalDate.parsewith no formatter needs the ISO formyyyy-MM-dd. - The pattern
dd-mm-yyyyprinted 40 (the minutes) where the month should be, with no error. Text in the wrong format throwsDateTimeParseExceptionwith the index where parsing failed.
DateTimeFormatter formats and parses. DateTimeFormatter.ofPattern("dd-MM-yyyy") handles Indian-style dates; MM is month and mm is minutes, a classic bug. Parsing text that does not match the pattern throws DateTimeParseException. Formatters are immutable and thread-safe, so one shared constant is fine. Revise: Period and Duration (opens in a new tab) and Formatting and parsing dates (opens in a new tab).
Must know:
Period.between(date1, date2)gives years, months and days (P3Y10M11D);Duration.between(time1, time2)gives hours, minutes and seconds (PT7H30M).ChronoUnit.DAYS.between(a, b)gives the total number of days as along.- Patterns:
ddday,MMmonth,MMMshort month name,yyyyyear,HH24-hour,hh12-hour,mmminutes,aAM/PM. LocalDate.parse("2026-06-05")uses the ISO format with no formatter.
Fix the error
Fix the date compile errors
Read the real compiler error, then pick the line that fixes it.
Round 1 of 2
How long is a shift from 09:00 to 17:30?
Error
PF1.java:6: error: incompatible types: LocalTime cannot be converted to LocalDate
Period gap = Period.between(LocalTime.of(9, 0), LocalTime.of(17, 30));
^Coding questions: age from birth date, days between dates
ChronoUnit is an enum of time units. ChronoUnit.DAYS.between(a, b) gives the total number of days between two dates as a long, and MONTHS and YEARS work the same way.
Two classic coding questions: age from a birth date, and days between two dates. The example passes a fixed "today" so the output never changes.
Example 5 · Age and days between, with a fixed today
import java.time.LocalDate;import java.time.Period;import java.time.temporal.ChronoUnit;
public class AgeDaysDemo { static int age(LocalDate birth, LocalDate today) { return Period.between(birth, today).getYears(); }
public static void main(String[] args) { LocalDate today = LocalDate.of(2026, 10, 16); // fixed so the output never changes
System.out.println("Age (born 2005-10-16): " + age(LocalDate.of(2005, 10, 16), today)); System.out.println("Age (born 2005-10-17): " + age(LocalDate.of(2005, 10, 17), today));
LocalDate placementDrive = LocalDate.of(2026, 12, 1); long days = ChronoUnit.DAYS.between(today, placementDrive); System.out.println("Days to placement drive: " + days);
LocalDate feeDue = LocalDate.of(2026, 10, 10); System.out.println("Days since fee due: " + ChronoUnit.DAYS.between(feeDue, today)); System.out.println("Is fee late? " + today.isAfter(feeDue)); System.out.println("Leap year 2028? " + LocalDate.of(2028, 1, 1).isLeapYear()); }}Age (born 2005-10-16): 21 Age (born 2005-10-17): 20 Days to placement drive: 46 Days since fee due: 6 Is fee late? true Leap year 2028? true
What this code does
Period.between(birth, today).getYears()gives 21 on the birthday and 20 one day before it, which is exactly how age works.todayis a parameter, so the output is the same on every run.ChronoUnit.DAYS.betweengives total days as along: 46 days to 1 December, and 6 days since the fee was due.
In code that must be tested, pass today in as a parameter (or use a Clock) instead of calling LocalDate.now() inside the method, so the result does not change every day. Revise: Comparing and adjusting dates (opens in a new tab).
Must know:
- Age is
Period.between(birthDate, today).getYears(). It counts full years only, so someone born tomorrow, 21 years ago, is still 20. - Do not divide days by 365: leap years make that wrong near birthdays.
- Days between two dates is
ChronoUnit.DAYS.between(start, end), alongthat is negative whenendis earlier. Period.between(...).getDays()is a common wrong answer: it returns only the days part after full months, not the total.
Order of execution
Age from a birth date
Tap the steps in the order the method does them.
Traps: immutability, months starting at 1, month-end and invalid dates
Most date bugs come from four habits. Run the example, then try the predictions to see each trap in action.
Example 6 · Find the bug: ignored result, month-end and invalid dates
import java.time.DateTimeException;import java.time.LocalDate;
public class TrapsDemo { public static void main(String[] args) { LocalDate due = LocalDate.of(2026, 1, 31);
due.plusDays(7); // result thrown away System.out.println("After plusDays without assignment: " + due); LocalDate later = due.plusDays(7); System.out.println("With assignment: " + later);
System.out.println("Jan 31 + 1 month: " + due.plusMonths(1)); System.out.println("Month 2 means: " + LocalDate.of(2026, 2, 1).getMonth());
try { LocalDate.of(2026, 2, 30); } catch (DateTimeException e) { System.out.println("Error: " + e.getMessage()); }
LocalDate a = LocalDate.of(2026, 5, 1); LocalDate b = LocalDate.parse("2026-05-01"); System.out.println("equals: " + a.equals(b) + ", isEqual: " + a.isEqual(b)); }}After plusDays without assignment: 2026-01-31 With assignment: 2026-02-07 Jan 31 + 1 month: 2026-02-28 Month 2 means: FEBRUARY Error: Invalid date 'FEBRUARY 30' equals: true, isEqual: true
What this code does
due.plusDays(7);on its own changes nothing: the new date is created and thrown away. Assigning it tolatergives 7 February.- Jan 31 plus one month clamps to Feb 28, and 30 February throws
DateTimeExceptioninstead of silently rolling over, unlike the oldCalendar.
Revise: LocalDate basics (opens in a new tab).
Must know:
- Every
java.timeobject is immutable, sodue.plusDays(7);without assigning the result does nothing (the same trap asString.toUpperCase()). - Months start at 1:
LocalDate.of(2026, 2, 1)is February (unlikeCalendar). - Adding months clamps to month-end: Jan 31 + 1 month is Feb 28 (or 29 in a leap year).
LocalDate.of(2026, 2, 30)throwsDateTimeException: Invalid date 'FEBRUARY 30'.- Compare dates with
isBefore,isAfter,isEqualorequals, never with==.
Predict the output
Date traps
Read each program and pick what it prints.
Round 1 of 4
plusMonths without using the result.
Next step
Check your understanding
12 quick questions