Sitemap

Java’s Duration.between() Method Explained

7 min readNov 29, 2024

--

Image Source

The Duration.between() method in Java is a powerful feature of the java.time package introduced in Java 8. This method calculates the time elapsed between two temporal objects, such as Instant or LocalDateTime. It provides an easy way to measure durations for tasks like tracking execution time, monitoring elapsed time, or implementing time-based systems.

In this article, we’ll explore how the Duration.between() method works, its real-world applications, and examples of its usage.

How the Duration.between() Method Works

The Duration.between() method calculates the time between two temporal points and returns a Duration object. The two arguments passed to the method must implement the Temporal interface, such as Instant, LocalDateTime, or ZonedDateTime.

Syntax

public static Duration between(Temporal startInclusive, Temporal endExclusive)
  • startInclusive: The starting temporal object (inclusive).
  • endExclusive: The ending temporal object (exclusive).

The resulting Duration represents the difference between the two temporal points, measured in seconds and nanoseconds.

Key Features

  1. Supports multiple temporal types: Works with Instant, LocalDateTime, and other compatible types.
  2. Accurate down to nanoseconds: Allows precise measurement of time differences.
  3. Immutable and thread-safe: The Duration object is immutable and safe for use across threads.

Alternatives to Duration.between()

While Duration.between() is a common choice for measuring time differences, there are alternative methods in Java that can achieve similar results. Here we will compare these alternatives, discuss their advantages and disadvantages, and outline the best practices for using them effectively.

Using ChronoUnit.between()

The ChronoUnit.between() method provides another way to calculate the difference between two temporal points. Instead of returning a Duration object, it directly gives the difference in a specific unit (e.g., seconds, minutes, or days).

Example:

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

public class ChronoUnitExample {
public static void main(String[] args) {
LocalDateTime start = LocalDateTime.of(2024, 10, 12, 9, 0);
LocalDateTime end = LocalDateTime.of(2024, 10, 12, 17, 0);

long hours = ChronoUnit.HOURS.between(start, end);
System.out.println("Difference in hours: " + hours);
}
}

Advantages:

  • Directly calculates the difference in a specific unit without the need to extract values from a Duration.
  • Easier to use for simple time differences like hours or days.

Disadvantages:

  • Limited to specific units and does not provide sub-second precision.
  • Not as flexible as Duration when multiple units (e.g., hours, minutes, and seconds) need to be combined.

Best Practice: Use ChronoUnit.between() when the time difference is needed in a single unit, such as days or hours, and sub-second precision is not required.

Using System.nanoTime() or System.currentTimeMillis()

System.nanoTime() provides a high-resolution time source for measuring elapsed time in nanoseconds, while System.currentTimeMillis() returns the current time in milliseconds since the Unix epoch (January 1, 1970). They are often used for performance benchmarking.

Example:

public class SystemTimeExample {
public static void main(String[] args) {
long start = System.nanoTime();

// Simulate a task
for (int i = 0; i < 1_000_000; i++) {
Math.sqrt(i);
}

long end = System.nanoTime();
System.out.println("Elapsed time: " + (end - start) + " nanoseconds");
}
}

Advantages:

  • Ideal for high-resolution time measurements, especially for performance-critical applications.
  • Lightweight and does not require temporal objects.

Disadvantages:

  • Provides only the elapsed time and not a Duration object, requiring manual conversion to seconds or other units.
  • Not tied to java.time API, making integration with modern date/time features less straightforward.

Best Practice: Use System.nanoTime() or System.currentTimeMillis() for benchmarking tasks or when you need raw elapsed time values without the overhead of creating temporal objects.

Using Custom Calculations with LocalDateTime or Instant

Manually calculating the difference between two time points by extracting and subtracting values is another approach.

Example:

import java.time.LocalDateTime;
import java.time.temporal.ChronoField;

public class ManualCalculationExample {
public static void main(String[] args) {
LocalDateTime start = LocalDateTime.of(2024, 10, 12, 9, 0);
LocalDateTime end = LocalDateTime.of(2024, 10, 12, 17, 0);

long seconds = end.getLong(ChronoField.SECOND_OF_DAY) - start.getLong(ChronoField.SECOND_OF_DAY);
System.out.println("Difference in seconds: " + seconds);
}
}

Note: This method works correctly when start and end are on the same day. For dates spanning multiple days, consider using toEpochSecond() for accurate results.

Get Alexander Obregon’s stories in your inbox

Join Medium for free to get updates from this writer.

Advantages:

  • Provides full control over how the difference is calculated.
  • Useful for custom calculations or when precise formatting is required.

Disadvantages:

  • More error-prone and verbose than using built-in methods.
  • Lacks the built-in precision and simplicity of Duration.between().

Best Practice: Use manual calculations only when the built-in methods cannot fulfill specific requirements.

Best Practices for Using Duration.between()

  1. Use Duration.between() for most scenarios: It offers a balance of precision, ease of use, and flexibility.
  2. Combine with other Duration methods: Methods like toHours(), toMinutes(), and toMillis() help extract meaningful units easily.
  3. Reserve alternatives for niche cases: Use ChronoUnit.between() or System.nanoTime() for specific needs like benchmarking or single-unit calculations.

Use Cases and Examples

Measuring Execution Time

Measuring the time it takes to complete a task or process is one of the most practical uses of Duration.between(). This feature is useful for evaluating the performance of code segments, optimizing algorithms, or monitoring runtime behavior.

Example — Tracking Task Execution Time
The following code demonstrates how to measure the execution time of a simulated task:

import java.time.Duration;
import java.time.Instant;

public class ExecutionTimeExample {
public static void main(String[] args) {
Instant start = Instant.now();

// Simulate a task with a delay
try {
Thread.sleep(2000); // Sleep for 2 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}

Instant end = Instant.now();
Duration duration = Duration.between(start, end);
System.out.println("Execution time: " + duration.toMillis() + " milliseconds");
}
}

This code tracks the time it takes to execute a simulated task and prints the duration in milliseconds. Developers can apply this pattern to measure the performance of various methods or blocks of code.

Tracking Elapsed Time

Tracking how much time has passed since a particular event or process began is another practical use of Duration.between(). This feature is especially useful in applications that involve time monitoring, such as games, session tracking, or countdown timers.

Example — Time Elapsed Since Program Start
The following example demonstrates tracking the time elapsed since a program started:

import java.time.Duration;
import java.time.Instant;

public class ElapsedTimeExample {
public static void main(String[] args) {
Instant programStart = Instant.now();

// Simulate operations
try {
Thread.sleep(1500); // Sleep for 1.5 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}

Instant currentTime = Instant.now();
Duration elapsed = Duration.between(programStart, currentTime);
System.out.println("Time elapsed: " + elapsed.toSeconds() + " seconds");
}
}

This example calculates the elapsed time since the program’s start in seconds, which is particularly helpful in scenarios where real-time feedback is needed.

Time Tracking for Real-World Applications

In practical applications such as time-tracking systems or logging frameworks, the Duration.between() method provides precise calculations for intervals between events. These calculations can help track user activity, record work sessions, or measure delays between actions.

Example — Tracking Work Session Duration
In this example, we calculate the duration of a hypothetical work session:

import java.time.LocalDateTime;
import java.time.Duration;

public class WorkSessionTracker {
public static void main(String[] args) {
LocalDateTime workStart = LocalDateTime.of(2024, 10, 12, 9, 0); // 9:00 AM
LocalDateTime workEnd = LocalDateTime.of(2024, 10, 12, 17, 0); // 5:00 PM

Duration workDuration = Duration.between(workStart, workEnd);
System.out.println("Work session duration: " + workDuration.toHours() + " hours");
}
}

This example outputs the duration of a standard work session in hours. Time-tracking software can use a similar pattern to calculate and log working hours for employees.

Measuring Delays Between Events

Duration.between() is also useful for analyzing delays or gaps between events. For instance, this feature can monitor the time between user actions in an application or measure the delay between receiving and processing data in a pipeline.

Example — Monitoring Delay Between Events

import java.time.Instant;
import java.time.Duration;

public class EventDelayExample {
public static void main(String[] args) {
Instant firstEvent = Instant.now();

// Simulate a delay before the second event
try {
Thread.sleep(2500); // Sleep for 2.5 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}

Instant secondEvent = Instant.now();
Duration delay = Duration.between(firstEvent, secondEvent);
System.out.println("Delay between events: " + delay.toMillis() + " milliseconds");
}
}

This code measures the delay between two simulated events and provides the duration in milliseconds. Applications in data processing and analytics can use similar patterns to monitor delays or latencies.

Implementing Countdown Timers

Countdown timers often need to calculate the remaining time until a specific event. By using Duration.between(), the remaining time can be computed easily and updated in real-time.

Example — Countdown Timer

import java.time.Duration;
import java.time.LocalDateTime;

public class CountdownTimer {
public static void main(String[] args) {
LocalDateTime eventTime = LocalDateTime.of(2024, 12, 31, 23, 59); // New Year's Eve
LocalDateTime currentTime = LocalDateTime.now();

Duration remainingTime = Duration.between(currentTime, eventTime);
System.out.println("Time remaining: " + remainingTime.toDays() + " days");
}
}

This example calculates the number of days remaining until a specific future event, such as New Year’s Eve. It demonstrates how Duration.between() can be utilized to create simple countdown applications.

Logging Time Differences in Applications

Logging frameworks and monitoring systems often need to record time intervals between events. By integrating Duration.between(), such systems can provide detailed time-based metrics.

Example — Logging Event Durations

import java.time.Instant;
import java.time.Duration;

public class LoggingExample {
public static void main(String[] args) {
Instant eventStart = Instant.now();

// Simulate some processing
try {
Thread.sleep(3000); // Sleep for 3 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}

Instant eventEnd = Instant.now();
Duration eventDuration = Duration.between(eventStart, eventEnd);
System.out.println("Event duration: " + eventDuration.toSeconds() + " seconds");
}
}

This example records the duration of an event, which can be incorporated into logging systems to track execution times or measure the effectiveness of processes.

Conclusion

The Duration.between() method offers a straightforward way to calculate time differences in Java. With its precision and flexibility, it is suitable for various use cases, from measuring execution times to tracking elapsed durations and implementing real-world applications like time tracking systems. Understanding its usage can help developers handle time-based calculations efficiently in their projects.

  1. Java Duration Class Documentation
  2. Java 8 Date and Time API Overview
  3. Introduction to Instant Class
  4. ChronoUnit Class

Thank you for reading! If you find this article helpful, please consider highlighting, clapping, responding or connecting with me on Twitter/X as it’s very appreciated and helps keeps content like this free!

--

--

Alexander Obregon
Alexander Obregon

I post daily about programming topics and share what I learn as I go. For recaps, exclusive content, and to support me: https://alexanderobregon.substack.com