Date and time: practice
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Most date bugs come from a short list: the wrong type for the value, a result that was never stored, a pattern letter in the wrong case, a day count that is off by one, and a time zone that was ignored. Each one is easy to fix once you can spot it.
Pick the right type first
Half of all date problems disappear when the type matches what the value really means. Ask: is this a calendar day, a clock time, a real moment, or a length of time?
Example 1 · An exam timetable printer
import java.time.Duration;import java.time.LocalDate;import java.time.LocalDateTime;import java.time.LocalTime;import java.time.format.DateTimeFormatter;import java.time.temporal.ChronoUnit;import java.util.ArrayList;import java.util.Comparator;import java.util.List;import java.util.Locale;
record Paper(String subject, LocalDate date, LocalTime start, Duration length) { LocalDateTime startsAt() { return date.atTime(start); }
LocalDateTime endsAt() { return startsAt().plus(length); }}
public class TimetableDemo { static final DateTimeFormatter DAY = DateTimeFormatter.ofPattern("EEE dd MMM yyyy", Locale.ENGLISH); static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH);
public static void main(String[] args) { List<Paper> papers = new ArrayList<>(); papers.add(new Paper("Physics", LocalDate.of(2024, 4, 3), LocalTime.of(10, 0), Duration.ofHours(3))); papers.add(new Paper("Maths", LocalDate.of(2024, 4, 1), LocalTime.of(10, 0), Duration.ofHours(3))); papers.add(new Paper("Chemistry Lab", LocalDate.of(2024, 4, 3), LocalTime.of(14, 30), Duration.ofMinutes(150))); papers.add(new Paper("English", LocalDate.of(2024, 4, 8), LocalTime.of(10, 0), Duration.ofMinutes(165))); papers.sort(Comparator.comparing(Paper::startsAt));
LocalDate previous = null; for (Paper p : papers) { String gap = previous == null ? "" : " (+" + ChronoUnit.DAYS.between(previous, p.date()) + " days)"; System.out.println(p.date().format(DAY) + " " + p.startsAt().format(TIME) + " - " + p.endsAt().format(TIME) + " " + p.subject() + gap); previous = p.date(); } }}Mon 01 Apr 2024 10:00 AM - 01:00 PM Maths Wed 03 Apr 2024 10:00 AM - 01:00 PM Physics (+2 days) Wed 03 Apr 2024 02:30 PM - 05:00 PM Chemistry Lab (+0 days) Mon 08 Apr 2024 10:00 AM - 12:45 PM English (+5 days)
What this code does
- A record keeps each paper's date, start time and length together, and
startsAt()andendsAt()combine them withatTimeandplus(Duration). Sorting bystartsAtputs two papers on the same day in time order. - Two
static finalformatters withLocale.ENGLISHgive the same text on every computer. The gap usesChronoUnit.DAYS.between, so two papers on one day show+0 days.
- Only a day (DOB, due date, holiday):
LocalDate. Only a clock time (class slot):LocalTime. Both, in one place:LocalDateTime. - A real moment seen from many zones (meeting, payment, log line):
ZonedDateTimeto show it,Instantto store it. - A calendar gap (age, notice period):
Period. An exact gap (exam length, ride time):Duration. One total number:ChronoUnit.X.between. - Text for people:
DateTimeFormatter.ofPattern(..., Locale.ENGLISH). Text for machines: the ISO constants.
Mistakes that print the wrong value
Every java.time object is immutable. A line like due.plusDays(7); builds a new date and throws it away, and the compiler says nothing. Always assign the result: due = due.plusDays(7);.
Example 2 · Fixing a wrong pattern and an ignored plusDays
import java.time.LocalDateTime;import java.time.format.DateTimeFormatter;
public class TwoBugsDemo { static String reminderBuggy(LocalDateTime due) { due.minusDays(2); return due.format(DateTimeFormatter.ofPattern("dd-mm-YYYY hh:mm")); }
static String reminderFixed(LocalDateTime due) { LocalDateTime remindAt = due.minusDays(2); return remindAt.format(DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm")); }
public static void main(String[] args) { LocalDateTime due = LocalDateTime.of(2025, 1, 1, 17, 45); System.out.println("Buggy: " + reminderBuggy(due)); System.out.println("Fixed: " + reminderFixed(due)); }}Buggy: 01-45-2025 05:45 Fixed: 30-12-2024 17:45
What this code does
- The buggy version throws away the result of
minusDays, prints the minute (45) where the month should be, and uses the 12-hour clock with no AM or PM, so 17:45 shows as05:45. - The fixed version stores the new date and uses
MM,yyyyandHH. The reminder lands on 30 December 2024; withYYYYthat date would print as 2025, because it falls in the first week of 2025.
Pattern letters are case-sensitive and the wrong case usually runs without an error. mm is minutes, MM is months. YYYY is the week-based year, which is wrong for a few days around New Year. hh without a hides AM and PM. When a printed date looks almost right, check every letter of the pattern.
Mistakes in counting days
Period.between(a, b).getDays() is only the days part, not the total. ChronoUnit.DAYS.between(a, b) is the total, and it does not count the end day. If a rule counts both days, such as "leave from 4 March to 8 March is 5 days", add 1.
import java.time.*;import java.time.temporal.ChronoUnit;
public class DayCounts { public static void main(String[] args) { LocalDate from = LocalDate.of(2024, 3, 4), to = LocalDate.of(2024, 4, 8); System.out.println(Period.between(from, to).getDays()); System.out.println(ChronoUnit.DAYS.between(from, to)); System.out.println(ChronoUnit.DAYS.between(from, to) + 1); LocalDate start = LocalDate.of(2024, 1, 31); System.out.println(start.plusMonths(1).plusMonths(1)); System.out.println(start.plusMonths(2)); }}4 35 36 2024-03-29 2024-03-31
plusMonths uses the last valid day when the day does not exist, so monthly dates must be built from the original start: start.plusMonths(i). A range check that includes both ends is !d.isBefore(start) && !d.isAfter(end).
Counting working days
A working day here means a day that is not a Saturday, Sunday or holiday. There is no single method for this; you walk through the dates and count.
Example 3 · Counting working days, with holidays
import java.time.DayOfWeek;import java.time.LocalDate;import java.time.temporal.ChronoUnit;import java.util.Set;
public class WorkingDaysDemo { static final Set<LocalDate> HOLIDAYS = Set.of( LocalDate.of(2024, 3, 25), // Holi LocalDate.of(2024, 3, 29)); // Good Friday
static boolean isWorkingDay(LocalDate d) { DayOfWeek day = d.getDayOfWeek(); return day != DayOfWeek.SATURDAY && day != DayOfWeek.SUNDAY && !HOLIDAYS.contains(d); }
// both ends included static int workingDaysLoop(LocalDate start, LocalDate end) { int count = 0; for (LocalDate d = start; !d.isAfter(end); d = d.plusDays(1)) { if (isWorkingDay(d)) { count++; } } return count; }
static long workingDaysStream(LocalDate start, LocalDate end) { return start.datesUntil(end.plusDays(1)) .filter(WorkingDaysDemo::isWorkingDay) .count(); }
public static void main(String[] args) { LocalDate start = LocalDate.of(2024, 3, 1); LocalDate end = LocalDate.of(2024, 3, 31); System.out.println("Calendar days: " + (ChronoUnit.DAYS.between(start, end) + 1)); System.out.println("Working days (loop): " + workingDaysLoop(start, end)); System.out.println("Working days (stream): " + workingDaysStream(start, end)); System.out.println("25 March is a working day? " + isWorkingDay(LocalDate.of(2024, 3, 25))); }}Calendar days: 31 Working days (loop): 19 Working days (stream): 19 25 March is a working day? false
What this code does
- The loop starts at
start, moves one day at a time withd = d.plusDays(1)and stops afterend, so both ends are checked. March 2024 has 21 weekdays; removing Holi and Good Friday leaves 19. datesUntilexcludes its end, so the stream version passesend.plusDays(1).ChronoUnit.DAYS.betweenalso excludes the end day, which is why the calendar day count adds 1.
Start at the first date, check it, move one day forward with plusDays(1), and stop after the last date.
Since Java 9, start.datesUntil(endExclusive) returns a Stream<LocalDate> of every date in the range, so the same count becomes filter(...) and count(). Keep holidays in a Set<LocalDate>, because contains on a set is fast.
now(); use fixed dates or a fixed Clock so the answer is the same every day.Example 4 · Was the assignment on time? A deadline across zones
import java.time.Duration;import java.time.Instant;import java.time.LocalDateTime;import java.time.ZoneId;import java.time.ZonedDateTime;
public class DeadlineDemo { public static void main(String[] args) { ZonedDateTime deadline = LocalDateTime.of(2024, 3, 31, 23, 59).atZone(ZoneId.of("Asia/Kolkata")); Instant deadlineInstant = deadline.toInstant(); System.out.println("Deadline (UTC): " + deadlineInstant);
// submissions are stored as Instants Instant fromLondon = Instant.parse("2024-03-31T18:00:00Z"); Instant fromChennai = Instant.parse("2024-03-31T18:40:00Z");
Instant[] subs = {fromChennai, fromLondon}; for (Instant s : subs) { boolean onTime = !s.isAfter(deadlineInstant); Duration diff = Duration.between(s, deadlineInstant).abs(); System.out.println(s + " on time=" + onTime + " (" + diff.toMinutes() + " min " + (onTime ? "early" : "late") + ")"); }
ZonedDateTime londonView = deadline.withZoneSameInstant(ZoneId.of("Europe/London")); System.out.println("Deadline on a London clock: " + londonView.toLocalDateTime() + " " + londonView.getOffset()); }}Deadline (UTC): 2024-03-31T18:29:00Z 2024-03-31T18:40:00Z on time=false (11 min late) 2024-03-31T18:00:00Z on time=true (29 min early) Deadline on a London clock: 2024-03-31T19:29 +01:00
What this code does
- 23:59 IST is 18:29 UTC. Comparing
Instantvalues removes every zone question: the London submission at 18:00 UTC is on time, and the Chennai one at 18:40 UTC is 11 minutes late, when the student's clock already showed 00:10 on 1 April. - London switched to summer time on 31 March 2024, so the deadline shows as 19:29 at
+01:00there.Duration.abs()turns a negative gap into a positive one for display.
Finish up
Mark complete & continue
Next: Records as data carriers in streams