Skip to lesson

Compare and adjust dates

Dates are objects, so Java compares them with methods such as isBefore and isAfter, not with < and >. To change a date, you ask for a new one: a few days later with plusDays, a set day with withDayOfMonth, or a rule like "the last day of the month" with a TemporalAdjuster.

Comparing dates: isBefore, isAfter, isEqual

Was the fee paid before the due date? Is the exam after the holiday? < and > work only on numbers, so paid < due does not compile for LocalDate. Use paid.isBefore(due), paid.isAfter(due) and paid.isEqual(due). Each returns a boolean.

Example 1 · Comparing and sorting dates

CompareDatesDemo.javaJava
import java.time.LocalDate;import java.util.ArrayList;import java.util.List;
public class CompareDatesDemo {    public static void main(String[] args) {        LocalDate due = LocalDate.of(2024, 3, 10);        LocalDate paid = LocalDate.of(2024, 3, 12);
        System.out.println("paid before due? " + paid.isBefore(due));        System.out.println("paid after due?  " + paid.isAfter(due));        System.out.println("paid on due?     " + paid.isEqual(due));        System.out.println("compareTo:       " + paid.compareTo(due));
        // text comparison gets the order wrong        System.out.println("\"05-04-2024\" < \"20-03-2024\" as text? " + ("05-04-2024".compareTo("20-03-2024") < 0));
        List<LocalDate> exams = new ArrayList<>();        exams.add(LocalDate.of(2024, 4, 5));        exams.add(LocalDate.of(2024, 3, 20));        exams.add(LocalDate.of(2024, 4, 1));        exams.sort(null);        System.out.println("Sorted: " + exams);    }}
Output
paid before due? false
paid after due?  true
paid on due?     false
compareTo:       2
"05-04-2024" < "20-03-2024" as text? true
Sorted: [2024-03-20, 2024-04-01, 2024-04-05]

What this code does

  • isBefore, isAfter and isEqual read like plain English and return a boolean. compareTo returns a positive number here because paid is later than due.
  • As text, 05-04-2024 sorts before 20-03-2024 although it is the later date. LocalDate is Comparable, so sorting a list of dates gives true calendar order.

Comparing the text instead is a classic bug. As text, "05-04-2024" comes before "20-03-2024" because 0 is smaller than 2, even though 5 April is later. Parse the text into dates first, then compare the dates. LocalDate also implements Comparable, so compareTo works and a List<LocalDate> sorts from earliest to latest with list.sort(null).

For a LocalDate, isEqual and equals give the same answer. They differ only for zoned values, covered in the time zones lesson.

Is a date inside a range?

Admissions are open from 1 April to 30 April, both days included. A date is inside when it is not before the start and not after the end: !d.isBefore(start) && !d.isAfter(end).

Example 2 · Inside a window, both ends included

AdmissionWindowDemo.javaJava
import java.time.LocalDate;
public class AdmissionWindowDemo {    static boolean insideWrong(LocalDate d, LocalDate start, LocalDate end) {        return d.isAfter(start) && d.isBefore(end);    }
    static boolean inside(LocalDate d, LocalDate start, LocalDate end) {        return !d.isBefore(start) && !d.isAfter(end);    }
    public static void main(String[] args) {        LocalDate start = LocalDate.of(2024, 4, 1);        LocalDate end = LocalDate.of(2024, 4, 30);        String[] tests = {"2024-03-31", "2024-04-01", "2024-04-15", "2024-04-30", "2024-05-01"};        for (String t : tests) {            LocalDate d = LocalDate.parse(t);            System.out.println(d + " wrong=" + insideWrong(d, start, end) + " right=" + inside(d, start, end));        }    }}
Output
2024-03-31 wrong=false right=false
2024-04-01 wrong=false right=true
2024-04-15 wrong=true right=true
2024-04-30 wrong=false right=true
2024-05-01 wrong=false right=false

What this code does

  • isAfter(start) && isBefore(end) leaves out both end days, so 1 April and 30 April are wrongly outside.
  • "Not before the start and not after the end" includes both ends. Testing the day before, both ends and the day after catches this kind of bug.

Writing d.isAfter(start) && d.isBefore(end) looks natural, but it leaves out the first and last day. A student who applies on 30 April would be told "closed". Decide on purpose whether each end is included, and test both ends.

plus, minus and the month-end rule

plusDays, plusWeeks, plusMonths, plusYears and their minus partners return new dates. There is also a general form, plus(3, ChronoUnit.MONTHS).

Example 3 · plusMonths and the month-end rule

MonthEndDemo.javaJava
import java.time.LocalDate;import java.time.temporal.ChronoUnit;
public class MonthEndDemo {    public static void main(String[] args) {        LocalDate jan31of2024 = LocalDate.of(2024, 1, 31);        LocalDate jan31of2023 = LocalDate.of(2023, 1, 31);
        System.out.println("2024-01-31 + 1 month:  " + jan31of2024.plusMonths(1));        System.out.println("2023-01-31 + 1 month:  " + jan31of2023.plusMonths(1));        System.out.println("2024-02-29 + 1 year:   " + LocalDate.of(2024, 2, 29).plusYears(1));        System.out.println("2024-03-31 - 1 month:  " + LocalDate.of(2024, 3, 31).minusMonths(1));        System.out.println("+1 month, then +1:     " + jan31of2024.plusMonths(1).plusMonths(1));        System.out.println("+2 months at once:     " + jan31of2024.plusMonths(2));        System.out.println("plus(10, DAYS):        " + jan31of2024.plus(10, ChronoUnit.DAYS));    }}
Output
2024-01-31 + 1 month:  2024-02-29
2023-01-31 + 1 month:  2023-02-28
2024-02-29 + 1 year:   2025-02-28
2024-03-31 - 1 month:  2024-02-29
+1 month, then +1:     2024-03-29
+2 months at once:     2024-03-31
plus(10, DAYS):        2024-02-10

What this code does

  • When the day does not exist in the new month, Java uses the last valid day: 29 February in 2024, 28 February in 2023. It never spills over into March.
  • Once a date has moved to the 29th, it stays on the 29th. That is why two single steps give 29 March but one step of two months gives 31 March.

Example 4 · Trap: an EMI schedule that drifts

EmiScheduleDemo.javaJava
import java.time.LocalDate;
public class EmiScheduleDemo {    public static void main(String[] args) {        LocalDate start = LocalDate.of(2024, 1, 31);
        System.out.print("Repeated adding: ");        LocalDate d = start;        for (int i = 1; i <= 4; i++) {            d = d.plusMonths(1);            System.out.print(d + " ");        }        System.out.println();
        System.out.print("From the start:  ");        for (int i = 1; i <= 4; i++) {            System.out.print(start.plusMonths(i) + " ");        }        System.out.println();    }}
Output
Repeated adding: 2024-02-29 2024-03-29 2024-04-29 2024-05-29 
From the start:  2024-02-29 2024-03-31 2024-04-30 2024-05-31

What this code does

  • Adding one month to the previous due date carries the February 29th forward, so every later EMI falls on the 29th instead of the month end.
  • start.plusMonths(i) measures each due date from the original day, so April correctly falls on the 30th and May on the 31st.

Months have different lengths, so plusMonths follows one rule: if the day does not exist in the new month, it uses the last valid day of that month. 31 January 2024 plus one month is 29 February 2024; in 2023 it is 28 February. 29 February 2024 plus one year is 28 February 2025. This rule has a side effect. Adding one month twice from 31 January gives 29 March, but adding two months at once gives 31 March. For monthly schedules such as EMIs, always add i months to the original start date.

with and TemporalAdjusters

with... methods set one part and keep the rest: withDayOfMonth(1), withMonth(12), withYear(2025). The day must exist, so withDayOfMonth(31) on an April date throws DateTimeException.

Example 5 · with and TemporalAdjusters

AdjustersDemo.javaJava
import java.time.DayOfWeek;import java.time.LocalDate;import java.time.temporal.TemporalAdjusters;
public class AdjustersDemo {    public static void main(String[] args) {        LocalDate d = LocalDate.of(2024, 3, 15);   // a Friday        System.out.println("Date:              " + d + " " + d.getDayOfWeek());        System.out.println("withDayOfMonth(1): " + d.withDayOfMonth(1));        System.out.println("withMonth(12):     " + d.withMonth(12));        System.out.println("Last day of month: " + d.with(TemporalAdjusters.lastDayOfMonth()));        System.out.println("First of next:     " + d.with(TemporalAdjusters.firstDayOfNextMonth()));        System.out.println("Next Monday:       " + d.with(TemporalAdjusters.next(DayOfWeek.MONDAY)));        System.out.println("Next Friday:       " + d.with(TemporalAdjusters.next(DayOfWeek.FRIDAY)));        System.out.println("Friday or same:    " + d.with(TemporalAdjusters.nextOrSame(DayOfWeek.FRIDAY)));        System.out.println("Second Saturday:   " + d.with(TemporalAdjusters.dayOfWeekInMonth(2, DayOfWeek.SATURDAY)));        System.out.println("Last Friday:       " + d.with(TemporalAdjusters.lastInMonth(DayOfWeek.FRIDAY)));    }}
Output
Date:              2024-03-15 FRIDAY
withDayOfMonth(1): 2024-03-01
withMonth(12):     2024-12-15
Last day of month: 2024-03-31
First of next:     2024-04-01
Next Monday:       2024-03-18
Next Friday:       2024-03-22
Friday or same:    2024-03-15
Second Saturday:   2024-03-09
Last Friday:       2024-03-29

What this code does

  • with... methods set one part and keep the rest. with(adjuster) moves the date by a rule, and the adjuster works out the month length and weekdays for you.
  • next(FRIDAY) on a Friday jumps a full week ahead, while nextOrSame(FRIDAY) keeps the same day. dayOfWeekInMonth(2, SATURDAY) finds the second Saturday, a bank holiday in India.
  • firstDayOfMonth(), lastDayOfMonth(), firstDayOfNextMonth(), firstDayOfYear(), lastDayOfYear()
  • next(DayOfWeek.MONDAY): strictly after the date. nextOrSame(...): the date itself if it is already a Monday.
  • previous(...) and previousOrSame(...) work the same way backwards.
  • firstInMonth(...), lastInMonth(...), dayOfWeekInMonth(2, DayOfWeek.SATURDAY) for "second Saturday".

For rules like "last day of this month" or "next Monday", java.time.temporal.TemporalAdjusters has ready-made adjusters. An adjuster is an object that knows how to move a date to a related date. You pass it to with: date.with(TemporalAdjusters.lastDayOfMonth()).

Real-world use: fee due dates and late fees

A college sets the fee due on the 10th of every month. If the 10th is a Sunday, the office is closed, so the due date moves to Monday. Payment after the due date adds a late fee.

Example 6 · Fee due date and late fee check

FeeDueDemo.javaJava
import java.time.DayOfWeek;import java.time.LocalDate;
public class FeeDueDemo {    static LocalDate dueDate(int year, int month) {        LocalDate due = LocalDate.of(year, month, 1).withDayOfMonth(10);        if (due.getDayOfWeek() == DayOfWeek.SUNDAY) {            due = due.plusDays(1);   // office closed: move to Monday        }        return due;    }
    static int lateFee(LocalDate paid, LocalDate due) {        if (!paid.isAfter(due)) {            return 0;        }        return paid.isAfter(due.plusDays(15)) ? 500 : 100;    }
    public static void main(String[] args) {        System.out.println("March due: " + dueDate(2024, 3));        System.out.println("April due: " + dueDate(2024, 4));
        LocalDate due = dueDate(2024, 3);        String[] payments = {"2024-03-09", "2024-03-11", "2024-03-12", "2024-03-26", "2024-03-27"};        for (String p : payments) {            LocalDate paid = LocalDate.parse(p);            System.out.println("Paid " + paid + " -> late fee Rs. " + lateFee(paid, due));        }    }}
Output
March due: 2024-03-11
April due: 2024-04-10
Paid 2024-03-09 -> late fee Rs. 0
Paid 2024-03-11 -> late fee Rs. 0
Paid 2024-03-12 -> late fee Rs. 100
Paid 2024-03-26 -> late fee Rs. 100
Paid 2024-03-27 -> late fee Rs. 500

What this code does

  • 10 March 2024 is a Sunday, so the March due date moves to Monday 11 March. 10 April is a Wednesday and stays.
  • Paying on the due date is not late, because the check is isAfter(due). A payment up to 15 days late costs Rs. 100; from day 16 it costs Rs. 500. The test dates sit on both sides of each boundary.

Each rule maps to one method: withDayOfMonth(10) for the 10th, a getDayOfWeek() check plus plusDays(1) for Sunday, and isAfter(due) for "late". Put the rules in small methods, then test them with fixed dates on both sides of every boundary: one day before, the day itself and one day after.

Next step

Check your understanding

12 quick questions