Close

Java Date Time - Duration.from() 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 from(TemporalAmount amount)

This method returns an instance of Duration object based on the provided TemporalAmount.

The provided temporal amount must have all fields needed for the Duration instance to be created otherwise DateTimeException will be thrown.

Examples


package com.logicbig.example.duration;

import java.time.Duration;

public class FromExample {

public static void main(String... args) {
Duration d = Duration.from(Duration.ofHours(30));
System.out.println(d);

d = Duration.from(Duration.ofHours(-30));
System.out.println(d);
}
}

Output

PT30H
PT-30H




package com.logicbig.example.duration;

import java.time.Duration;
import java.time.LocalDate;
import java.time.Period;

public class FromExample2 {

public static void main(String... args) {
Period p = Period.between(LocalDate.now(), LocalDate.ofYearDay(2020, 3));
System.out.println(p);

Duration d2 = Duration.from(p);
System.out.println(d2);
}
}

Output

Caused by: java.time.temporal.UnsupportedTemporalTypeException: Unit must not have an estimated duration
at java.time.Duration.plus(Duration.java:701)
at java.time.Duration.from(Duration.java:336)
at com.logicbig.example.duration.FromExample2.main(FromExample2.java:18)
... 6 more




See Also