Thursday, September 18, 2025
HomeLanguagesJavaDuration from(TemporalUnit) method in Java with Examples

Duration from(TemporalUnit) method in Java with Examples

The from(TemporalUnit) method of Duration Class in java.time package is used to get a duration from the amount passed as the first parameter in the TemporalUnit. The TemporalUnit can be DAYS, HOURS, etc.

Syntax:

public static Duration from(TemporalUnit amount)

Parameters: This method accepts a parameter amount which is amount from which the Duration is to be found, passed as the TemporalUnit.

Return Value: This method returns a Duration representing the time of specified amount.

Exception: This method throws following unit:

  • ArithmeticException: if numeric overflow occurs.
  • DateTimeException: if unable to convert to a Duration

Below examples illustrate the Duration.from() method:

Example 1:




// Java code to illustrate from() method
  
import java.time.Duration;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Get the amount
        Duration duration = Duration.ofDays(5);
  
        // Duration using from() method
        Duration duration1 = Duration.from(duration);
  
        System.out.println(duration1.getSeconds());
    }
}


Output:

432000

Example 2:




// Java code to illustrate from() method
  
import java.time.Duration;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // Get the amount
        Duration duration = Duration.ofHours(5);
  
        // Duration using from() method
        Duration duration1 = Duration.from(duration);
  
        System.out.println(duration1.getSeconds());
    }
}


Output:

18000

Reference: Oracle Doc

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32299 POSTS0 COMMENTS
Milvus
84 POSTS0 COMMENTS
Nango Kala
6663 POSTS0 COMMENTS
Nicole Veronica
11835 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11895 POSTS0 COMMENTS
Shaida Kate Naidoo
6779 POSTS0 COMMENTS
Ted Musemwa
7053 POSTS0 COMMENTS
Thapelo Manthata
6736 POSTS0 COMMENTS
Umr Jansen
6742 POSTS0 COMMENTS