Java - Date Time Durations

Introduction

Duration class represents an amount of time between two instants on the timeline.

The Duration value can be a positive as well as negative.

Create Duration

You can create an instance of the Duration class using one of its ofXXX() static factory methods.

// A duration of 2 days
Duration d1 = Duration.ofDays(2);

// A duration of 25 minutes
Duration d2 = Duration.ofMinutes(25);

instants records timestamps. Durations records elapsed time between two events.

Two instants can be compared to know whether one occurs before or after other.

You can add (and subtract) a duration to an instant to obtain another instant.

Adding two durations results in another duration.

The following is an example of getting second and nanosecond of an Instant:

Demo

import java.time.Instant;

public class Main {
  public static void main(String[] args) {
    // Get the current instant
    Instant i1 = Instant.now();

    // Get seconds and nanoseconds
    long seconds = i1.getEpochSecond();
    int nanoSeconds = i1.getNano();

    System.out.println("Current Instant: " + i1);
    System.out.println("Seconds: " + seconds);
    System.out.println("Nanoseconds: " + nanoSeconds);

  }//from  www  .  j a  v a2  s . co m
}

Result

The following code demonstrates use of some operations that can be performed on instants and durations.

Demo

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

public class Main {
        public static void main(String[] args) {
                Instant i1 = Instant.ofEpochSecond(20);
                Instant i2 = Instant.ofEpochSecond(55);
                System.out.println("i1:" + i1);
                System.out.println("i2:" + i2);

                Duration d1 = Duration.ofSeconds(55);
                Duration d2 = Duration.ofSeconds(-17);
                System.out.println("d1:" + d1);
                System.out.println("d2:" + d2);

                // Compare instants
                System.out.println("i1.isBefore(i2):" + i1.isBefore(i2));
                System.out.println("i1.isAfter(i2):" + i1.isAfter(i2));

                // Add and subtract durations to instants
                Instant i3 = i1.plus(d1);
                Instant i4 = i2.minus(d2);
                System.out.println("i1.plus(d1):" + i3);
                System.out.println("i2.minus(d2):" + i4);

                // Add two durations
                Duration d3 = d1.plus(d2);
                System.out.println("d1.plus(d2):" + d3);
        }//from   w ww  .  j av a2s  . c o m
}

Result