Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Duration

An amount of time in seconds and nanoseconds — hours, minutes, seconds.

Available since: Java 8

Syntax

public final class Duration implements TemporalAmount, Comparable<Duration>

Examples

The duration between two moments:

void main() {
    LocalTime start = LocalTime.of(9, 15);
    LocalTime end = LocalTime.of(17, 45);
    Duration work = Duration.between(start, end);
    IO.println(work);
    IO.println(work.toMinutes());
    IO.println(work.toHours() + "h " + work.toMinutesPart() + "m");
}

Output:

PT8H30M
510
8h 30m

Creating one and adding it to a time:

void main() {
    Duration timeout = Duration.ofSeconds(90);
    IO.println(timeout);
    IO.println(LocalTime.of(10, 0).plus(timeout));
    IO.println(Duration.ofMinutes(45).plusHours(1).toMinutes());
}

Output:

PT1M30S
10:01:30
105

Notes

toString() prints the ISO-8601 format: PT8H30M is 8 hours 30 minutes. For people, build a string from toHoursPart(), toMinutesPart(), toSecondsPart() (Java 9). For calendar days, months and years use Period. To time code, use System.nanoTime() or Instant.now().

See also

  • Period — A calendar amount in years, months and days — for example, an age.
  • ChronoUnit.between() — Counts the whole units (days, months, hours) between two dates or moments.
  • Instant — An exact moment on the UTC timeline — for logs, timestamps and measurements.
  • LocalTime — A time of day without a date — for example, a shop's opening time.

Related recipes

In the tutorial

  • Dates and times — The java.time package — LocalDate, LocalTime, LocalDateTime, date arithmetic, Period, Duration, ChronoUnit, time zones and Instant.

Thanks for reading!

Donate to the site — we work hard for you.