Saturday, December 13, 2025
HomeLanguagesJavaChronoPeriod get() method in Java with Examples

ChronoPeriod get() method in Java with Examples

The get() method of ChronoPeriod interface in Java is used to get the value of the requested unit(YEARS, MONTHS or DAYS) given in the argument from this ChronoPeriod.

Syntax:

long get(TemporalUnit unit)

Parameters: This method accepts a single parameter unit of type TemporalUnit which is the unit to get required unit.

Return Value: This function returns the long value of the requested unit.

Exceptions:

  • DateTimeException – This method throws DateTimeException, if the unit in argument is not supported.
  • UnsupportedTemporalTypeException – This method throws UnsupportedTemporalTypeException if the unit given in argument is not supported.

Below programs illustrate the above method:

Program 1:




// Java code to show the function get()
// which gives the requested unit
  
import java.time.*;
import java.time.chrono.*;
import java.time.temporal.ChronoUnit;
  
public class ChronoPeriodDemo {
  
    // Function to get requested unit
    static void getUnit(int year, int months, int days)
    {
        ChronoPeriod period = Period.of(year, months, days);
        System.out.println(period.get(ChronoUnit.DAYS));
    }
  
    // Driver Code
    public static void main(String[] args)
    {
  
        int year = 8;
        int months = 5;
        int days = 25;
  
        getUnit(year, months, days);
    }
}


Output:

25

Program 2:




// Java code to show the function get()
// which gives the requested unit
  
import java.time.*;
import java.time.chrono.*;
import java.time.temporal.ChronoUnit;
  
public class ChronoPeriodDemo {
  
    // Function to get requested unit
    static void getUnit(int year, int months, int days)
    {
        ChronoPeriod period = Period.of(year, months, days);
        System.out.println(period.get(ChronoUnit.YEARS));
    }
  
    // Driver Code
    public static void main(String[] args)
    {
  
        int year = 11;
        int months = 3;
        int days = 21;
  
        getUnit(year, months, days);
    }
}


Output:

11

Reference: https://docs.oracle.com/javase/9/docs/api/java/time/chrono/ChronoChronoPeriod.html#get-java.time.temporal.TemporalUnit-

RELATED ARTICLES

Most Popular

Dominic
32446 POSTS0 COMMENTS
Milvus
105 POSTS0 COMMENTS
Nango Kala
6814 POSTS0 COMMENTS
Nicole Veronica
11952 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12030 POSTS0 COMMENTS
Shaida Kate Naidoo
6949 POSTS0 COMMENTS
Ted Musemwa
7200 POSTS0 COMMENTS
Thapelo Manthata
6897 POSTS0 COMMENTS
Umr Jansen
6882 POSTS0 COMMENTS