java.time
java.time has one class per idea: a date without a time, a time without a date, a moment on the timeline, an amount of time and a calendar period. They are immutable values, so a method returns a new object, and they know the calendar rules that a program written with three integers always gets wrong.
LocalDate
A date is built with a year, a month and a day, printed in ISO form, and asked for the facts a calendar has:
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
public class Dates {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2024, Month.JANUARY, 31);
System.out.println("start: " + date);
System.out.println("plus one month: " + date.plusMonths(1));
System.out.println("plus one day: " + date.plusDays(1));
System.out.println("month length: " + date.lengthOfMonth());
System.out.println("leap: " + date.isLeapYear());
System.out.println("next monday: " + date.with(TemporalAdjusters.next(DayOfWeek.MONDAY)));
System.out.println("last day: " + date.with(TemporalAdjusters.lastDayOfMonth()));
System.out.println("day of week: " + date.getDayOfWeek());
System.out.println("days to 2025: " + ChronoUnit.DAYS.between(date, LocalDate.of(2025, 1, 1)));
System.out.println("after february: " + LocalDate.of(2024, 2, 29).plusYears(1));
}
}
javac -Xlint:all Dates.java
java Dates
start: 2024-01-31
plus one month: 2024-02-29
plus one day: 2024-02-01
month length: 31
leap: true
next monday: 2024-02-05
last day: 2024-01-31
day of week: WEDNESDAY
days to 2025: 336
after february: 2025-02-28
Arithmetic across a month
The first two lines are the lesson. One month after the 31st of January is the 29th of February, because the month has no 31st and the class takes the last day it has. The last line shows the same rule a year later: the 29th of February plus a year is the 28th, because 2025 is not a leap year.
That is why a date is not three integers. A program that keeps a month and a day and adds days by itself has to know the length of every month and the leap rule, and it will be wrong for the year 2100, which is not a leap year although 2000 was. lengthOfMonth and isLeapYear are the two facts it would need, and plusMonths is the operation that uses them.
LocalTime and Duration
A time of day is a number of nanoseconds since midnight, and a Duration is a number of seconds and nanoseconds with no date attached. The pair answers the length of a working day:
import java.time.Duration;
import java.time.LocalTime;
public class Times {
public static void main(String[] args) {
LocalTime start = LocalTime.of(9, 30);
LocalTime end = LocalTime.of(17, 45);
Duration work = Duration.between(start, end);
System.out.println("start: " + start);
System.out.println("end: " + end);
System.out.println("duration: " + work);
System.out.println("minutes: " + work.toMinutes());
System.out.println("plus 90: " + start.plusMinutes(90));
System.out.println("truncated: " + LocalTime.of(14, 37, 52).truncatedTo(java.time.temporal.ChronoUnit.HOURS));
System.out.println("negative: " + Duration.between(end, start));
System.out.println("zero: " + Duration.ofSeconds(0).isZero());
}
}
javac -Xlint:all Times.java
java Times
start: 09:30
end: 17:45
duration: PT8H15M
minutes: 495
plus 90: 11:00
truncated: 14:00
negative: PT-8H-15M
zero: true
The toString of a duration is the ISO 8601 form: PT8H15M is a period of time, eight hours and fifteen minutes. The negative value prints with its sign on each part, which is a form to read and not to parse by hand; the numbers are what a program uses.
Period and Instant
A Period is a calendar amount, in years, months and days, which is what a person means by "two years and a day". An Instant is the other kind of time: a point on the line of seconds since 1970, which is what a computer stores:
import java.time.Instant;
import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
public class Periods {
public static void main(String[] args) {
LocalDate from = LocalDate.of(2024, 2, 29);
LocalDate to = LocalDate.of(2026, 3, 1);
Period period = Period.between(from, to);
System.out.println("period: " + period);
System.out.println("years: " + period.getYears() + " months: " + period.getMonths() + " days: " + period.getDays());
System.out.println("total months: " + period.toTotalMonths());
System.out.println("formatted: " + from.format(DateTimeFormatter.ISO_LOCAL_DATE));
System.out.println("parsed: " + LocalDate.parse("2026-11-20"));
Instant instant = Instant.ofEpochMilli(1_700_000_000_000L);
System.out.println("instant: " + instant);
System.out.println("at utc: " + instant.atZone(ZoneOffset.UTC).toLocalDate());
System.out.println("epoch second: " + instant.getEpochSecond());
}
}
javac -Xlint:all Periods.java
java Periods
period: P2Y1D
years: 2 months: 0 days: 1
total months: 24
formatted: 2024-02-29
parsed: 2026-11-20
instant: 2023-11-14T22:13:20Z
at utc: 2023-11-14
epoch second: 1700000000
From the 29th of February 2024 to the 1st of March 2026 is two years and one day: the period adds the years first, landing on the last day of February 2026, and then the day. The total of months is 24, because the day is not a whole month. The Z at the end of the instant is UTC, and the same moment is a different local date in another time zone, which is why a program stores an instant and converts it when it prints.
Rules for time
Store an Instant in a database and convert it to a LocalDate or a ZonedDateTime only when a person reads it. Use Period for a calendar amount and Duration for a number of seconds, and do not mix the two: a month is not thirty days, and a program that treats it as one is wrong twice a year. Name the time zone where a time of day matters. And let the library do the arithmetic, because the leap year of 2100 is in the future of every test.
The old classes Date and Calendar are still in the JDK and are not what a new program uses: they are mutable, their months count from zero, and they carry a time zone in a field. The formatting of a date for a reader is the next lesson; the classes here are the values it formats.
Exercises
- Print the number of days in each month of 2024 with a loop over Month.values().
- Find the first Friday of the next month with a TemporalAdjuster.
- Add 45 minutes to 23:30 and print the time.
- Convert an Instant to a date in two time zones and compare.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
LocalDate.of(2024, 1, 31).plusMonths(1)answer?Answer
2024-02-29, the last day of the shorter month
The month has no 31st, so the result is the last day the month has.
-
What is a Duration?
Answer
An amount of time in seconds and nanoseconds
Duration is the machine amount, and Period is the calendar one.
-
What does the Z at the end of an Instant mean?
Answer
UTC, as in the ISO 8601 form of a moment
An instant is on the timeline, and Z is the UTC designator of the format.
-
What does this program print?
import java.time.LocalDate; public class Q1 { public static void main(String[] args) { LocalDate d = LocalDate.of(2023, 2, 28); System.out.println(d.plusDays(1)); System.out.println(d.plusYears(1).getDayOfMonth()); } }Answer
2023-03-01 / 28
2023 is not a leap year, so the day after the 28th is the 1st of March.
-
Why is a date not three integers?
Answer
The month length and the leap rule have to be known by whatever adds to it
The class owns the calendar rules, which is why plusMonths gives the 29th of February.
-
What does
ChronoUnit.DAYS.between(a, b)answer?Answer
The number of whole days from a to b
The unit decides what is counted, and between answers how many of them fit.
-
Why does a program store an Instant rather than a LocalDate?
Answer
An instant is a point on the timeline, and a date depends on the time zone
The same moment is two dates in two zones, so the moment is what the program keeps.
-
What does this program print?
import java.time.Duration; import java.time.LocalTime; public class Q2 { public static void main(String[] args) { LocalTime a = LocalTime.of(10, 0); LocalTime b = LocalTime.of(11, 30); System.out.println(Duration.between(a, b).toMinutes()); System.out.println(a.plusHours(2).plusMinutes(15)); } }Answer
90 / 12:15
The difference is an hour and a half, and the second line adds two hours and a quarter.
-
What does this program print?
import java.time.LocalDate; import java.time.Period; public class Q3 { public static void main(String[] args) { Period p = Period.of(1, 14, 0); System.out.println(p); System.out.println(p.toTotalMonths()); } }Answer
P1Y14M / 26
The period keeps fourteen months as given, and the total adds the twelve of the year.
-
Why are Date and Calendar not what a new program uses?
Answer
They are mutable, their months count from zero and they carry a zone in a field
The java.time classes are immutable values, and the old ones are kept for compatibility.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev