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.
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.
First, open a text editor and create a new Java file called LocalDateGetYear.java
in the ~/project
directory.
cd ~/project
touch LocalDateGetYear.java
The following code block is used to import the necessary class.
import java.time.LocalDate;
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);
Call the getYear()
method on the LocalDate
object created earlier to get the year of the date.
int year = localDate.getYear();
Print the year to the console using the System.out.println()
method.
System.out.println("Year of date: " + year);
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
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);
}
}
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);
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);
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
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.