Java Period, Duration, Instant and Daylight Saving Time (OCP 21)
Amounts of time on the OCP Java 21 exam: Period for years, months and days, Duration for hours down to nanoseconds, their toString formats, ChronoUnit.between and truncatedTo, which types accept which amount, Instant, and how ZonedDateTime handles US daylight saving time.
kvi5hnuCode Sprout team member10 min readOn this page
The previous article was about points on the calendar: a date, a time, or both. This one is about amounts of time: "every three months", "90 minutes", "how long did that take?". java.time has two amount classes, and choosing the right one matters. Period counts calendar units (years, months and days), and Duration counts clock units (hours, minutes, seconds and nanoseconds). The article ends with Instant and with how ZonedDateTime deals with daylight saving time.
Period: years, months and days
Suppose a method sends reminders from a start date until an end date. Hard-coding plusMonths(1) in the loop would fix the interval forever. Passing a Period lets the caller choose:
static void schedule(LocalDate first, LocalDate end, Period every) {
var next = first;
while (next.isBefore(end)) {
System.out.println("reminder: " + next);
next = next.plus(every);
}
}
schedule(LocalDate.of(2026, 1, 15), LocalDate.of(2026, 6, 1), Period.ofMonths(1));
schedule(LocalDate.of(2026, 1, 15), LocalDate.of(2026, 6, 1), Period.ofWeeks(6));
There are five static factory methods:
var yearly = Period.ofYears(1); // P1Y
var quarterly = Period.ofMonths(3); // P3M
var backwards = Period.ofWeeks(-3); // P-21D (negative: back in time)
var everyOther = Period.ofDays(2); // P2D
var yearAndTen = Period.of(1, 0, 10); // P1Y10D (years, months, days)
A Period stores only three numbers: years, months and days. Weeks are a convenience: ofWeeks(2) is stored as 14 days, so it prints as P14D and is equals to Period.ofDays(14). Period.of takes exactly three int values. There's no version with weeks and no version with two arguments.
Don't chain the factory methods
var wrong = Period.ofYears(1).ofWeeks(1); // P7D: only one week!
ofWeeks is a static method. Calling it through the result of ofYears(1) compiles, but that result is ignored, so the line means the same as Period.ofWeeks(1). With -Xlint, javac warns that a static method should be called through the type name. Use Period.of(1, 0, 7) when you need several units.
How a Period prints
The format comes from ISO-8601: a P, then the years (Y), months (M) and days (D), with zero parts left out:
| Code | Output |
|---|---|
Period.of(1, 2, 3) | P1Y2M3D |
Period.ofMonths(3) | P3M |
Period.ofWeeks(3) | P21D |
Period.of(0, 15, 0) | P15M (not converted to years) |
Period.of(0, 15, 0).normalized() | P1Y3M |
Period.ZERO | P0D |
Period doesn't convert 15 months to 1 year 3 months, or 40 days to months, on its own. normalized() converts months to years, but never days to months, because months have different lengths.
Between two dates
Period.between(start, end) measures the distance between two LocalDate values, and the order matters:
var newYear = LocalDate.of(2027, 1, 1);
Period.between(LocalDate.of(2026, 12, 20), newYear); // P12D
Period.between(newYear, LocalDate.of(2026, 12, 20)); // P-12D
Duration: hours, minutes, seconds and nanoseconds
Duration is the clock-based counterpart: it's for amounts measured in hours, minutes and seconds. Internally, it's just a number of seconds plus nanoseconds. It has one factory method per unit, and no method that combines several units:
Duration.ofDays(2); // PT48H (a day is exactly 24 hours here)
Duration.ofHours(1); // PT1H
Duration.ofMinutes(135); // PT2H15M
Duration.ofSeconds(10); // PT10S
Duration.ofMillis(2250); // PT2.25S
Duration.ofNanos(1); // PT0.000000001S
The generic Duration.of(long amount, TemporalUnit unit) takes a ChronoUnit constant (from java.time.temporal), such as Duration.of(90, ChronoUnit.MINUTES). ChronoUnit has some less common units too, such as HALF_DAYS (12 hours).
The output starts with PT ("period of time"), followed by hours, minutes and seconds, with zero parts left out. Fractions of a second appear in the seconds part. Days are never shown, so 25 hours prints as PT25H, not P1DT1H. Negative amounts print each part with its sign: Duration.ofSeconds(-75) is PT-1M-15S.
Measuring with ChronoUnit and Duration.between
var open = LocalTime.of(8, 40);
var close = LocalTime.of(17, 15);
Duration.between(open, close); // PT8H35M
ChronoUnit.HOURS.between(open, close); // 8 (truncated, not rounded)
ChronoUnit.MINUTES.between(open, close);// 515
ChronoUnit.HOURS.between(close, open); // -8 (order matters)
ChronoUnit.X.between returns a long and truncates toward zero. Both arguments must support the unit, and the second must be convertible to the type of the first. Mixing a LocalTime with a LocalDate throws a DateTimeException. Duration.between needs time-based values, so calling it on two LocalDate objects throws UnsupportedTemporalTypeException ("Unsupported unit: Seconds"). Use Period.between or ChronoUnit.DAYS.between for dates.
Truncating
Types that have a time part have truncatedTo(TemporalUnit), which zeroes out every field smaller than the unit:
LocalTime.of(17, 15, 42, 900).truncatedTo(ChronoUnit.MINUTES); // 17:15
LocalDateTime.of(2026, 1, 20, 3, 12).truncatedTo(ChronoUnit.DAYS); // 2026-01-20T00:00
LocalDate has no truncatedTo method at all, so calling it is a compile error.
Which types accept which amount?
Pass an amount to plus or minus and Java adds each of its stored units to the target. If the target lacks one of those units, the call compiles (the parameter type is the TemporalAmount interface) and then throws UnsupportedTemporalTypeException at run time:
Period | Duration | |
|---|---|---|
LocalDate | yes | no ("Unsupported unit: Seconds") |
LocalTime | no ("Unsupported unit: Days" or "Months") | yes |
LocalDateTime | yes | yes |
ZonedDateTime | yes | yes |
Instant | days only | yes |
var date = LocalDate.of(2026, 5, 20);
var time = LocalTime.of(22, 0);
date.plus(Period.ofDays(1)); // 2026-05-21
date.plus(Duration.ofDays(1)); // UnsupportedTemporalTypeException
time.plus(Duration.ofHours(5)); // 03:00 (wraps around midnight)
time.plus(Period.ofDays(1)); // UnsupportedTemporalTypeException
A Duration.ofDays(1) may look like a day, but it's stored as 86,400 seconds, and a LocalDate has no seconds. A Period and a Duration can describe the "same" amount and still behave differently, so they're never interchangeable.
Instant: a point on the UTC time line
An Instant is a single moment, stored as seconds and nanoseconds since the epoch (1970-01-01T00:00). It has no time zone and no calendar fields, and it always prints in UTC with a trailing Z:
var zoned = ZonedDateTime.of(LocalDate.of(2026, 5, 24), LocalTime.of(11, 55),
ZoneId.of("America/New_York"));
Instant instant = zoned.toInstant();
System.out.println(zoned); // 2026-05-24T11:55-04:00[America/New_York]
System.out.println(instant); // 2026-05-24T15:55:00Z
System.out.println(instant.atZone(ZoneId.of("Asia/Kolkata")));
// 2026-05-24T21:25+05:30[Asia/Kolkata]
Notice that Instant.toString() always shows the seconds, even when they're zero.
To get an Instant from a ZonedDateTime, call toInstant(). A LocalDateTime can't be turned into an Instant on its own, because "11 on 24 May" is a different moment in every zone. You have to say where it is, either with atZone(zone) or with toInstant(ZoneOffset).
Instant.now() together with Duration.between is the usual way to time a piece of code:
var start = Instant.now();
doWork();
var elapsed = Duration.between(start, Instant.now());
System.out.println(elapsed.toMillis() + " ms");
Instant can add a Duration, and a Period or ChronoUnit of days, because a day is treated as exactly 24 hours on the UTC line. Months and years throw UnsupportedTemporalTypeException, because an Instant has no calendar.
Daylight saving time
Many regions move their clocks forward by an hour in spring and back by an hour in autumn. The exam uses US rules only, and a question will tell you when a date falls on a changeover weekend. In the US, the change happens at 2 a.m. local time on a Sunday: the second Sunday in March and the first Sunday in November. In 2026, those are March 8 and November 1.

Spring forward: an hour that doesn't exist
On 8 March 2026, New York clocks go from 01:59 straight to 03, and the offset changes from -05:00 to -04:00. Adding one hour to 01 gives 03:30:
var ny = ZoneId.of("America/New_York");
var t = ZonedDateTime.of(LocalDate.of(2026, 3, 8), LocalTime.of(1, 30), ny);
System.out.println(t); // 2026-03-08T01:30-05:00[America/New_York]
System.out.println(t.plusHours(1)); // 2026-03-08T03:30-04:00[America/New_York]
Check this in UTC: 01 − (−5) is 06 UTC, and 03 − (−4) is 07 UTC. Exactly one hour passed, even though the clock moved by two.
If you ask for a local time inside the gap, Java doesn't throw an exception. It moves the time forward by the length of the gap:
ZonedDateTime.of(LocalDate.of(2026, 3, 8), LocalTime.of(2, 30), ny);
// 2026-03-08T03:30-04:00[America/New_York]
Fall back: an hour that happens twice
On 1 November 2026, the clocks go from 01:59 back to 01, so every time from 01 to 01 happens twice, first with offset -04:00 and then with -05:00:
var f = ZonedDateTime.of(LocalDate.of(2026, 11, 1), LocalTime.of(1, 30), ny);
System.out.println(f); // 2026-11-01T01:30-04:00[America/New_York]
System.out.println(f.plusHours(1)); // 2026-11-01T01:30-05:00[America/New_York]
System.out.println(f.plusHours(2)); // 2026-11-01T02:30-05:00[America/New_York]
In UTC, these are 05, 06 and 07:30: one hour apart each time. When you create an ambiguous local time with of, Java picks the earlier offset (-04:00). withLaterOffsetAtOverlap() switches to the other one.
A day isn't always 24 hours
var noon = ZonedDateTime.of(LocalDate.of(2026, 3, 7), LocalTime.NOON, ny);
noon.plusDays(1); // 2026-03-08T12:00-04:00 (same clock time, 23 hours later)
noon.plusHours(24); // 2026-03-08T13:00-04:00 (exactly 24 hours later)
plusDays and Period work on the local calendar and keep the clock time. plusHours and Duration work on the time line and add exact elapsed time. On a changeover weekend, they give different answers.
What's current
- Java 23 added
Instant.until(Instant), which returns aDuration. It's equivalent toDuration.between(a, b)and isn't on 1Z0-830. - Nothing else here changed in Java 22 through 25.
Period,Durationand the daylight-saving rules behave identically on Java 21 and 25.
Exam traps from this article
A complete example
The program schedules reminders with two periods, prints the Period and Duration formats, measures opening hours, tries each kind of amount on each type, converts a zoned time to an Instant, and walks through both 2026 daylight saving changes in New York.
import java.time.DateTimeException;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAmount;
public class Solution {
static final ZoneId NEW_YORK = ZoneId.of("America/New_York");
// One reusable method: the caller decides how far apart the reminders are.
static void schedule(LocalDate first, LocalDate end, Period every) {
var next = first;
var out = new StringBuilder();
while (next.isBefore(end)) {
out.append(next).append(' ');
next = next.plus(every);
}
System.out.println(every + " -> " + out.toString().trim());
}
static void tryAdd(String label, Temporal target, TemporalAmount amount) {
try {
System.out.printf("%-22s %s%n", label, target.plus(amount));
} catch (DateTimeException e) {
System.out.printf("%-22s %s: %s%n", label, e.getClass().getSimpleName(), e.getMessage());
}
}
public static void main(String[] args) {
System.out.println("== Period: years, months, days");
var start = LocalDate.of(2026, Month.JANUARY, 15);
var end = LocalDate.of(2026, Month.JUNE, 1);
schedule(start, end, Period.ofMonths(1));
schedule(start, end, Period.ofWeeks(6));
System.out.println(Period.of(1, 0, 10) + " " + Period.ofWeeks(2) + " " + Period.of(0, 15, 0)
+ " " + Period.of(0, 15, 0).normalized() + " " + Period.ZERO);
var newYear = LocalDate.of(2027, 1, 1);
System.out.println(Period.between(LocalDate.of(2026, 12, 20), newYear) + " "
+ Period.between(newYear, LocalDate.of(2026, 12, 20)));
System.out.println("\n== Duration: hours, minutes, seconds");
System.out.println(Duration.ofDays(2) + " " + Duration.ofMinutes(135) + " " + Duration.ofMillis(2250)
+ " " + Duration.of(1, ChronoUnit.HALF_DAYS) + " " + Duration.ofSeconds(-75));
var open = LocalTime.of(8, 40);
var close = LocalTime.of(17, 15);
System.out.println("open for " + Duration.between(open, close) + " = "
+ ChronoUnit.HOURS.between(open, close) + " whole hours = "
+ ChronoUnit.MINUTES.between(open, close) + " minutes");
System.out.println("truncated: " + LocalTime.of(17, 15, 42, 900).truncatedTo(ChronoUnit.MINUTES));
System.out.println("\n== Which types accept which amount");
var date = LocalDate.of(2026, 5, 20);
var time = LocalTime.of(22, 0);
var dateTime = LocalDateTime.of(date, time);
tryAdd("LocalDate + Period", date, Period.ofDays(1));
tryAdd("LocalDate + Duration", date, Duration.ofDays(1));
tryAdd("LocalTime + Period", time, Period.ofDays(1));
tryAdd("LocalTime + Duration", time, Duration.ofHours(5));
tryAdd("LocalDateTime + both", dateTime.plus(Period.ofDays(1)), Duration.ofHours(5));
System.out.println("\n== Instant: one moment on the UTC time line");
var zoned = ZonedDateTime.of(LocalDate.of(2026, 5, 24), LocalTime.of(11, 55), NEW_YORK);
Instant instant = zoned.toInstant();
System.out.println(zoned + " = " + instant);
System.out.println(instant.atZone(ZoneId.of("Asia/Kolkata")));
var t0 = Instant.now();
long sum = 0;
for (int i = 0; i < 1_000_000; i++) {
sum += i;
}
var elapsed = Duration.between(t0, Instant.now());
System.out.println("sum " + sum + ", elapsed is not negative: " + !elapsed.isNegative());
System.out.println("\n== US daylight saving time 2026 (New York)");
var spring = ZonedDateTime.of(LocalDate.of(2026, 3, 8), LocalTime.of(1, 30), NEW_YORK);
System.out.println(spring + " +1h -> " + spring.plusHours(1));
System.out.println("02:30 does not exist -> "
+ ZonedDateTime.of(LocalDate.of(2026, 3, 8), LocalTime.of(2, 30), NEW_YORK));
var fall = ZonedDateTime.of(LocalDate.of(2026, 11, 1), LocalTime.of(1, 30), NEW_YORK);
System.out.println(fall + " +1h -> " + fall.plusHours(1) + " +1h -> " + fall.plusHours(2));
System.out.println("\n== A 'day' is not always 24 hours");
var noonBefore = ZonedDateTime.of(LocalDate.of(2026, 3, 7), LocalTime.NOON, NEW_YORK);
System.out.println("plusDays(1): " + noonBefore.plusDays(1));
System.out.println("plusHours(24): " + noonBefore.plusHours(24));
System.out.println("real length of that day: " + Duration.between(noonBefore, noonBefore.plusDays(1)));
}
}
Output:
== Period: years, months, days
P1M -> 2026-01-15 2026-02-15 2026-03-15 2026-04-15 2026-05-15
P42D -> 2026-01-15 2026-02-26 2026-04-09 2026-05-21
P1Y10D P14D P15M P1Y3M P0D
P12D P-12D
== Duration: hours, minutes, seconds
PT48H PT2H15M PT2.25S PT12H PT-1M-15S
open for PT8H35M = 8 whole hours = 515 minutes
truncated: 17:15
== Which types accept which amount
LocalDate + Period 2026-05-21
LocalDate + Duration UnsupportedTemporalTypeException: Unsupported unit: Seconds
LocalTime + Period UnsupportedTemporalTypeException: Unsupported unit: Days
LocalTime + Duration 03:00
LocalDateTime + both 2026-05-22T03:00
== Instant: one moment on the UTC time line
2026-05-24T11:55-04:00[America/New_York] = 2026-05-24T15:55:00Z
2026-05-24T21:25+05:30[Asia/Kolkata]
sum 499999500000, elapsed is not negative: true
== US daylight saving time 2026 (New York)
2026-03-08T01:30-05:00[America/New_York] +1h -> 2026-03-08T03:30-04:00[America/New_York]
02:30 does not exist -> 2026-03-08T03:30-04:00[America/New_York]
2026-11-01T01:30-04:00[America/New_York] +1h -> 2026-11-01T01:30-05:00[America/New_York] +1h -> 2026-11-01T02:30-05:00[America/New_York]
== A 'day' is not always 24 hours
plusDays(1): 2026-03-08T12:00-04:00[America/New_York]
plusHours(24): 2026-03-08T13:00-04:00[America/New_York]
real length of that day: PT23H
Points to notice:
Period.ofWeeks(6)prints asP42D, because weeks are stored as days.tryAddtakes theTemporalandTemporalAmountinterfaces, so every combination compiles. The errors appear only at run time.LocalTimeplusDuration.ofHours(5)wraps from 22 to 03. ALocalDateTimerolls into the next date instead.- The timing loop prints only whether the elapsed time is negative, so the output doesn't depend on how fast the machine is.
- On 7–8 March,
plusDays(1)andplusHours(24)give different times, andDuration.betweenshows that the "day" lasted 23 hours.
Common questions
Can a Period hold hours, or a Duration hold months?
No. Period has only years, months and days, and Duration has only seconds and nanoseconds. For a mix such as "2 days and 3 hours", add a Period and a Duration separately to a LocalDateTime or ZonedDateTime.
How do I read the parts of a Duration?
toHours(), toMinutes() and toMillis() convert the whole amount to one unit. Since Java 9, toHoursPart(), toMinutesPart() and toSecondsPart() return the individual parts, which is handy for output like 1:02:05.
Is Period.between the same as ChronoUnit.DAYS.between?
No. Period.between(Jan 1, Mar 15) is P2M14D (months and days), but ChronoUnit.DAYS.between returns 73, the total number of days.
Does every country use the US daylight saving dates?
No. The EU changes clocks on the last Sunday of March and October at 01 UTC, and many countries don't use daylight saving at all. The exam only asks about the US rules, but ZonedDateTime applies the correct rules for whatever ZoneId you use.
What's OffsetDateTime?
It's like ZonedDateTime, but with a fixed offset and no region rules, so it never adjusts for daylight saving time. It's common in databases and network formats. It isn't on the exam.
Summary
Periodholds years, months and days. Create it withof,ofYears,ofMonths,ofWeeksorofDays(don't chain them), and read it in theP1Y2M3Dformat.Durationholds seconds and nanoseconds. Create it withofDaysthroughofNanosorof(amount, ChronoUnit), and read it in thePT1H2M3Sformat.Periodworks with date-based types andDurationwith time-based ones. A mismatch compiles and then throwsUnsupportedTemporalTypeException.ChronoUnit.X.betweentruncates,truncatedTozeroes the smaller fields, andInstantis a UTC moment, which you get from aZonedDateTimewithtoInstant().- In the US, clocks spring forward at 2 a.m. in March (that hour doesn't exist) and fall back in November (that hour repeats).
ZonedDateTimeadjusts the offset, so elapsed time stays correct.
Practice quiz
Test yourself with the Period, Duration, Instant and daylight saving quiz: 10 exam-style questions with explanations.
Finished Chapter 4? Take the Chapter 4 review: Core APIs: 20 mixed questions covering strings, StringBuilder, arrays, Math and the date and time API.
Previous: Java Date and Time: LocalDate, LocalTime, LocalDateTime and ZonedDateTime (OCP 21)
Next: Java Method Declarations: Access Modifiers, Specifiers, Return Types and Parameters (OCP 21)
Related reading
- Java Date and Time: LocalDate, LocalTime, LocalDateTime and ZonedDateTime (OCP 21)
- Java Math API, BigInteger and BigDecimal (OCP 21)
- Java Arrays: equals, compare, mismatch, Varargs and Multidimensional Arrays (OCP 21)
- Java Arrays: Creating, Sorting and Searching (OCP 21)
- Java String Equality: ==, equals, the String Pool and intern (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.