Date and Time Arithmetic

Basic Java
≈ 2 min read

Plus and minus return new values

Dates and times regularly need to be moved forward and backward: set a deadline one week from now, get the start of the next month, subtract 30 minutes, or compare two dates. In java.time, this is done with plus... and minus... methods.

LocalDate date = LocalDate.of(2026, 9, 18);

LocalDate nextWeek = date.plusWeeks(1);
LocalDate previousMonth = date.minusMonths(1);

The original object does not change. This is the same immutability model we have already seen in the core date and time classes.

Calendar arithmetic respects the actual date

Adding a month is not the same as adding a fixed number of days. If the target month is shorter, Java adjusts the day to the last valid value.

LocalDate date = LocalDate.of(2026, 1, 31);
LocalDate result = date.plusMonths(1);

System.out.println(result); // 2026-02-28

This keeps the code close to business phrases such as “one month later,” but it also means you need to understand that calendar units do not have a fixed length in seconds.

Comparison

Date and time values provide isBefore(), isAfter(), and isEqual() methods. They are usually easier to read than manually interpreting the result of compareTo().

LocalDate deadline = LocalDate.of(2026, 9, 30);
LocalDate today = LocalDate.of(2026, 9, 18);

if (today.isBefore(deadline)) {
    System.out.println("There is still time");
}

Distance between values

For specific tasks, the interval classes we already know are convenient. Duration.between() measures a time-based duration, while Period.between() measures the calendar difference between dates.

LocalDate start = LocalDate.of(2026, 9, 18);
LocalDate end = LocalDate.of(2026, 12, 25);

Period period = Period.between(start, end);

Changing one field with with

with... methods create a copy of a value with one component replaced.

LocalDate date = LocalDate.of(2026, 9, 18);
LocalDate firstDay = date.withDayOfMonth(1);
Do not convert a calendar task into milliseconds unless necessary. Months, years, and local days follow calendar and time-zone rules. Numeric arithmetic is convenient for exact durations, but it does not replace the calendar model.