Java LocalDate get() Method with Examples

In this article we are going to see the use of Java LocalDate class get()  method with suitable examples.

Java LocalDate get() Method with Examples

Explanation:

This java.time.LocalDate.get(TemporalField field) method is used to get the value of the specified field from this date as an integer. It returns the value for field.

Exceptions:

  • DateTimeException –it occurs when the value is outside the range of valid values for the field.
  • UnsupportedTemporalTypeException − it occurs if the field is not supported or the range of values exceeds an integer value.
  • ArithmeticException − it occurs when the numeric overflow occurs.

Syntax:

public int get(TemporalField field)

Let’s see a program to understand it more clearly.

Approach:

  • Create an object of LocalDate class.
  • Then use the get method followed by specific command to get the required result.
  • Print the final result.

Program:

import java.time.LocalDate;
import java.time.temporal.ChronoField;
public class Main
{
    public static void main(String[] args)
    {
        //Create an object of LocalDate class and assign a date to it
        //here it parses the local date
        LocalDate date = LocalDate.parse("2022-05-10");
        //print the result by mentioning the specific item
      	System.out.println("Result: "+date.get(ChronoField.DAY_OF_MONTH)); 
   }
}
Output:

Result: 10

Let’s see an instance of exception with a program.

Approach:

  • Create an objects of LocalDate class which will hold the parsed dates.
  • Here we pass an invalid date for testing.
  • Then use the get method followed by specific command to get the required result.
  • Put all those code inside the try block and in catch block to check the exception.
  • Then print the final result.

Program:

import java.time.LocalDate;
import java.time.temporal.ChronoField;
public class Main
{
    public static void main(String[] args)
    {
        try
        {
            //Create an object of LocalDate class and assign a date to it
            //here it parses the local date
            LocalDate date = LocalDate.parse("2022-02-31");
            //print the result by mentioning the specific item
      	    System.out.println("Result: "+date.get(ChronoField.DAY_OF_MONTH));
        }
        catch(Exception excp)
        {
            //print the exception as result
            System.out.println(excp);
        } 
    }
}
Output:

java.time.format.DateTimeParseException: Text '2022-02-31' could not be parsed: Invalid date 'FEBRUARY 31'

Are you new to the java programming language? We recommend you to ace up your practice session with these Basic Java Programs Examples.