Java Calculate Number of Nanoseconds Between two OffsetDateTime

Tags: Java OffsetDateTime ChronoUnit Java 8

In this Java core tutorial, we learn how to calculate the number of nanoseconds between two OffsetDateTime objects using the java.time.temporal.ChronoUnit class in Java programming language.

How to get number of nanoseconds between two OffsetDateTime in Java

In Java, we can use the ChronoUnit.NANOS.between() method to calculate the number of nanoseconds between two OffsetDateTime values as the following example Java code.

NanosecondsBetweenOffsetDateTimeExample.java

import java.time.OffsetDateTime;
import java.time.temporal.ChronoUnit;

public class NanosecondsBetweenOffsetDateTimeExample {
    public static void main(String... args) {
        OffsetDateTime startOffsetDateTime = OffsetDateTime.parse("2022-08-14T07:00:00.00+07:00");
        OffsetDateTime endOffsetDateTime = OffsetDateTime.parse("2022-08-14T07:00:01.00+07:00");

        // Calculate Number of Nanoseconds Between two OffsetDateTime
        long numberOfNanoseconds = ChronoUnit.NANOS.between(startOffsetDateTime, endOffsetDateTime);

        System.out.println(String.format("Number of nanoseconds between %s and %s is %d",
                startOffsetDateTime,
                endOffsetDateTime,
                numberOfNanoseconds));
    }
}
The output as below.
Number of nanoseconds between 2022-08-14T07:00+07:00 and 2022-08-14T07:00:01+07:00 is 1000000000

Happy Coding 😊

Java Calculate Number of Decades Between two OffsetDateTime

Java Calculate Number of Years Between two OffsetDateTime

Java Calculate Number of Months Between two OffsetDateTime

Java Calculate Number of Weeks Between two OffsetDateTime

Java Calculate Number of Days Between two OffsetDateTime

Java Calculate Number of Hours Between two OffsetDateTime

Java Calculate Number of Minutes Between two OffsetDateTime

Java Calculate Number of Seconds Between two OffsetDateTime

Java Calculate Number of Milliseconds Between two OffsetDateTime