Close

Java Date Time - Duration.of() Examples

Java Date Time Java Java API 


Class:

java.time.Duration

java.lang.Objectjava.lang.Objectjava.time.Durationjava.time.Durationjava.time.temporal.TemporalAmountTemporalAmountjava.lang.ComparableComparablejava.io.SerializableSerializableLogicBig

Method:

public static Duration of(long amount,
                          TemporalUnit unit)

Creates a Duration object representing the provided amount in the specified unit.

Examples


package com.logicbig.example.duration;

import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.time.temporal.UnsupportedTemporalTypeException;

public class OfExample {

public static void main(String... args) {
for (ChronoUnit unit : ChronoUnit.values()) {
try {
Duration d = Duration.of(2, unit);
System.out.printf("Duration of 2 %s : %s%n", unit, d);
} catch (UnsupportedTemporalTypeException e) {
System.out.printf("Duration of unit %s not supported %n", unit);
}
}
}
}

Output

Duration of 2 Nanos : PT0.000000002S
Duration of 2 Micros : PT0.000002S
Duration of 2 Millis : PT0.002S
Duration of 2 Seconds : PT2S
Duration of 2 Minutes : PT2M
Duration of 2 Hours : PT2H
Duration of 2 HalfDays : PT24H
Duration of 2 Days : PT48H
Duration of unit Weeks not supported
Duration of unit Months not supported
Duration of unit Years not supported
Duration of unit Decades not supported
Duration of unit Centuries not supported
Duration of unit Millennia not supported
Duration of unit Eras not supported
Duration of unit Forever not supported




See Also