Java LocalDate getYear Method

JavaJavaBeginner
Practice Now

Introduction

The getYear() method in Java LocalDate class returns the year of a date. In this lab, we will learn how to use the getYear() method with examples.

Create a Java Class

First, open a text editor and create a new Java file called LocalDateGetYear.java in the ~/project directory.

cd ~/project
touch LocalDateGetYear.java

Import necessary class

The following code block is used to import the necessary class.

import java.time.LocalDate;

Create a LocalDate object

Create a LocalDate object specifying a particular date of which you want to get the year from. In this example, we will use the date "2021-10-10".

LocalDate localDate = LocalDate.of(2021, 10, 10);

Get the year from LocalDate object

Call the getYear() method on the LocalDate object created earlier to get the year of the date.

int year = localDate.getYear();

Print the year

Print the year to the console using the System.out.println() method.

System.out.println("Year of date: " + year);

Compile and Run the code

Save the file and close the text editor. Open the terminal and navigate to the ~/project directory. Type the following command to compile the code.

javac LocalDateGetYear.java

Then, type the following command to run the code.

java LocalDateGetYear

Complete the Code

The complete code for the LocalDateGetYear.java file should look like this:

import java.time.LocalDate;

public class LocalDateGetYear {
    public static void main(String[] args) {
        LocalDate localDate = LocalDate.of(2021, 10, 10);
        int year = localDate.getYear();
        System.out.println("Year of date: " + year);
    }
}

Test with Different Dates

Modify the date used in the LocalDate.of() method to test the code with different dates.

LocalDate localDate = LocalDate.of(2000, 12, 31);
int year = localDate.getYear();
System.out.println("Year of date: " + year);

Use LocalDate.now() method to get current date

Instead of specifying a specific date, get the current date using the now() method of the LocalDate class.

LocalDate localDate = LocalDate.now();
int year = localDate.getYear();
System.out.println("Year of date: " + year);

Compile and Run the code

Save the file and close the text editor. Open the terminal and navigate to the ~/project directory. Type the following command to compile the code.

javac LocalDateGetYear.java

Then, type the following command to run the code.

java LocalDateGetYear

Summary

In this lab, we have learned how to use the getYear() method of the LocalDate class to get the year of a date in Java. We have also learned how to create a LocalDate object, call its getYear() method, and print the year to the console. We have also seen how to use the now() method to get the current date and get its year.

Other Java Tutorials you may like