Duration
In Javaβs Date-Time API, the Duration
class is designed to represent a span of time measured in seconds and nanoseconds. It is especially useful for calculating elapsed time between two temporal points or for representing time-based amounts like stopwatch durations or timeout intervals.
Instant
sThe Instant
class represents a point on the global timeline (UTC), ideal for measuring elapsed time with precision.
import java.time.Duration;
import java.time.Instant;
public class DurationExample {
public static void main(String[] args) throws InterruptedException {
Instant start = Instant.now();
// Simulate a task that takes some time
Thread.sleep(1500); // Sleep for 1.5 seconds
Instant end = Instant.now();
Duration elapsed = Duration.between(start, end);
System.out.println("Elapsed time in seconds: " + elapsed.getSeconds());
System.out.println("Elapsed time in milliseconds: " + elapsed.toMillis());
}
}
Output:
Elapsed time in seconds: 1
Elapsed time in milliseconds: 1502
Here, Duration.between()
computes the time difference accurately even across seconds and milliseconds.
LocalTime
sYou can also measure durations between two LocalTime
instances, such as for a daily stopwatch or event timing.
import java.time.Duration;
import java.time.LocalTime;
public class LocalTimeDuration {
public static void main(String[] args) {
LocalTime start = LocalTime.of(10, 15, 30);
LocalTime end = LocalTime.of(12, 45, 15);
Duration duration = Duration.between(start, end);
System.out.println("Duration: " + duration.toHoursPart() + " hours, "
+ duration.toMinutesPart() + " minutes, " + duration.toSecondsPart() + " seconds");
}
}
Output:
Duration: 2 hours, 29 minutes, 45 seconds
Note: Methods like toHoursPart()
, toMinutesPart()
, and toSecondsPart()
(available since Java 9) help break down the duration into components.
Duration
ManuallyYou can create durations directly by specifying time amounts using static factory methods:
Duration d1 = Duration.ofHours(2);
Duration d2 = Duration.ofMinutes(30);
Duration d3 = Duration.ofSeconds(45);
System.out.println(d1); // PT2H
System.out.println(d2); // PT30M
System.out.println(d3); // PT45S
The ISO-8601 string format like PT2H
stands for "period of time 2 hours."
Imagine building a stopwatch application that measures elapsed time between start and stop:
Instant start = Instant.now();
// ... user does some work
Instant stop = Instant.now();
Duration elapsed = Duration.between(start, stop);
System.out.printf("Elapsed time: %d minutes %d seconds%n",
elapsed.toMinutesPart(), elapsed.toSecondsPart());
This lets you accurately measure and display how long an operation or event took.
The Duration
class is the go-to utility for measuring and representing elapsed time in Java. It provides convenient ways to calculate differences between temporal objects like Instant
or LocalTime
, create durations manually, and extract hours, minutes, and seconds for display or logic. This makes it ideal for real-world scenarios such as stopwatches, timeouts, and performance measurements.
Period
While Duration
measures time in seconds and nanoseconds, the Period
class in Java represents date-based amounts β specifically years, months, and days. Itβs ideal for expressing intervals like an age, subscription length, or the time remaining until an event based on calendar dates.
Period
Using Period.of()
You can create a period by explicitly specifying years, months, and days:
import java.time.Period;
public class PeriodExample {
public static void main(String[] args) {
Period period = Period.of(2, 3, 10); // 2 years, 3 months, 10 days
System.out.println("Period: " + period);
}
}
Output:
Period: P2Y3M10D
This ISO-8601 string format indicates a period of 2 years, 3 months, and 10 days.
Period.between()
calculates the difference between two LocalDate
instances as a Period
:
import java.time.LocalDate;
import java.time.Period;
public class AgeCalculator {
public static void main(String[] args) {
LocalDate birthDate = LocalDate.of(1990, 4, 25);
LocalDate today = LocalDate.now();
Period age = Period.between(birthDate, today);
System.out.printf("Age is %d years, %d months, and %d days.%n",
age.getYears(), age.getMonths(), age.getDays());
}
}
Sample output:
Age is 35 years, 1 months, and 28 days.
This is useful in domains like healthcare, where age calculation influences treatment decisions.
You can parse a period directly from an ISO-8601 string representation using Period.parse()
:
Period billingCycle = Period.parse("P1Y6M"); // 1 year, 6 months
System.out.println("Billing cycle period: " + billingCycle);
This could represent a recurring billing cycle of 18 months.
LocalDate expirationDate = LocalDate.of(2026, 12, 31);
Period timeLeft = Period.between(LocalDate.now(), expirationDate);
System.out.println("Time until expiration: " + timeLeft);
Period monthlyBilling = Period.ofMonths(1);
LocalDate nextBillingDate = LocalDate.now().plus(monthlyBilling);
System.out.println("Next billing date: " + nextBillingDate);
The Period
class offers a natural way to work with date-based intervals involving years, months, and days. By using Period.of()
, Period.between()
, and Period.parse()
, you can easily model and manipulate durations for age calculations, expiration countdowns, billing cycles, and other calendar-based use cases β making your date-time logic clear, readable, and robust.
Javaβs Date-Time API allows you to add or subtract amounts of time or dates conveniently using the Duration
and Period
classes. Understanding the distinction between these two classes and how to apply them to temporal objects like LocalDateTime
is key to writing reliable date-time code.
Duration
Duration
measures time in terms of seconds and nanoseconds, making it perfect for operations involving hours, minutes, and seconds.
import java.time.Duration;
import java.time.LocalDateTime;
public class DurationExample {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
Duration twoHours = Duration.ofHours(2);
LocalDateTime later = now.plus(twoHours);
System.out.println("Current time: " + now);
System.out.println("After adding 2 hours: " + later);
// Subtracting 30 minutes
LocalDateTime earlier = now.minus(Duration.ofMinutes(30));
System.out.println("After subtracting 30 minutes: " + earlier);
}
}
Output:
Current time: 2025-06-22T14:20:35.123
After adding 2 hours: 2025-06-22T16:20:35.123
After subtracting 30 minutes: 2025-06-22T13:50:35.123
Period
Period
represents date-based amounts like years, months, and days, ideal for calendar arithmetic.
import java.time.LocalDateTime;
import java.time.Period;
public class PeriodExample {
public static void main(String[] args) {
LocalDateTime today = LocalDateTime.now();
Period tenDays = Period.ofDays(10);
LocalDateTime futureDate = today.plus(tenDays);
System.out.println("Today: " + today);
System.out.println("After adding 10 days: " + futureDate);
// Subtracting 1 month
LocalDateTime pastDate = today.minus(Period.ofMonths(1));
System.out.println("After subtracting 1 month: " + pastDate);
}
}
Output:
Today: 2025-06-22T14:20:35.123
After adding 10 days: 2025-07-02T14:20:35.123
After subtracting 1 month: 2025-05-22T14:20:35.123
Duration
and Period
Without Care?Duration counts time precisely as seconds/nanoseconds, ignoring calendar variations. Adding a Duration
of 24 hours always adds exactly 24 hours, even across daylight saving time boundaries.
Period deals with human calendar concepts β months and years can vary in length. Adding a month to January 31st, for example, results in February 28th or 29th depending on the year.
Mixing them carelessly can lead to subtle bugs:
LocalDateTime dateTime = LocalDateTime.of(2025, 3, 8, 1, 30);
// Daylight saving change in some zones occurs on this date
// Adding 1 day as Period moves the date calendar-wise
LocalDateTime afterPeriod = dateTime.plus(Period.ofDays(1));
// Adding 24 hours as Duration adds exact time
LocalDateTime afterDuration = dateTime.plus(Duration.ofHours(24));
System.out.println("Original: " + dateTime);
System.out.println("After adding Period of 1 day: " + afterPeriod);
System.out.println("After adding Duration of 24 hours: " + afterDuration);
The Period
-based addition shifts the calendar day forward, which might adjust the time if a daylight saving transition happens. The Duration
-based addition adds exactly 24 hours, which might land at a different local time.
Duration
when working with precise time intervals (hours, minutes, seconds).Period
when dealing with calendar-based changes (years, months, days).By correctly applying these classes, you ensure your time calculations remain intuitive and bug-free.
Duration
, Period
, and UnitsIn Javaβs Date-Time API, Duration
and Period
represent different concepts of time intervals. Understanding how to convert them into units like seconds, milliseconds, or into their components is essential for practical time calculations. This section explores these conversions and their limitations.
Duration
to Seconds and MillisecondsSince Duration
measures time in seconds and nanoseconds, it can easily be converted into total seconds or milliseconds using its built-in methods:
import java.time.Duration;
public class DurationConversion {
public static void main(String[] args) {
Duration duration = Duration.ofHours(1).plusMinutes(30).plusSeconds(45);
long totalSeconds = duration.getSeconds();
long totalMillis = duration.toMillis();
System.out.println("Duration: " + duration);
System.out.println("Total seconds: " + totalSeconds);
System.out.println("Total milliseconds: " + totalMillis);
}
}
Output:
Duration: PT1H30M45S
Total seconds: 5445
Total milliseconds: 5445000
Here, getSeconds()
returns the total seconds part of the duration (including hours and minutes converted to seconds), and toMillis()
converts the whole duration into milliseconds.
Period
Unlike Duration
, Period
represents a human calendar-based interval of years, months, and days. You can extract these components individually:
import java.time.Period;
public class PeriodComponents {
public static void main(String[] args) {
Period period = Period.of(2, 3, 15);
int years = period.getYears();
int months = period.getMonths();
int days = period.getDays();
System.out.println("Period: " + period);
System.out.println("Years: " + years);
System.out.println("Months: " + months);
System.out.println("Days: " + days);
}
}
Output:
Period: P2Y3M15D
Years: 2
Months: 3
Days: 15
These components are useful for displaying the duration or performing calendar-aware calculations.
Period
to MillisecondsA key limitation is that Period
cannot be directly converted to a precise duration like milliseconds or seconds because the length of months and years varies. For example:
Therefore, converting a Period
to a fixed number of milliseconds would be ambiguous without a reference start date.
Convert Duration
to seconds/milliseconds when you need precise elapsed times or intervals (e.g., for timers, delays, or performance measurement).
Use Period
components (years, months, days) for calendar-aware calculations, such as calculating age, subscription periods, or date-based billing cycles.
To convert a Period
to an exact duration, you must apply it to a specific start date and then calculate the Duration
between the start and resulting date:
import java.time.Duration;
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
public class PeriodToDuration {
public static void main(String[] args) {
LocalDate start = LocalDate.of(2025, 1, 1);
Period period = Period.ofMonths(1);
LocalDate end = start.plus(period);
long daysBetween = ChronoUnit.DAYS.between(start, end);
Duration durationApprox = Duration.ofDays(daysBetween);
System.out.println("Approximate duration for 1 month: " + durationApprox);
}
}
Since the actual number of days in a month varies, this method provides only an approximate duration.
Duration
can be precisely converted to seconds or milliseconds and is ideal for time-based intervals.Period
is split into calendar components and cannot be directly converted into fixed time units.Understanding these differences helps prevent errors in time calculations and improves the robustness of your date-time handling code.