We can use the getYear() method of the LocalDate class of Java 8 to get the year field value from date.
It returns an integer value as a result that actually represents the year of the date. We can also use it to fetch the current year from the date.
To get the current date in Java, use the now() method of the LocalDate class and then use the getYear() method to get the current year.
We have examples here that explain the whole process. So have a look.
import java.time.LocalDate;
/*
* Code example to Get Year from local date in Java
*/
public class JExercise {
public static void main(String[] args) {
// Some Date
String date = "2012-11-15";
LocalDate localDate = LocalDate.parse(date);
System.out.println("Date: "+localDate);
// Year
int year = localDate.getYear();
System.out.println("Year: "+year);
}
}
Output:
Date: 2021-02-22
Year: 2021
import java.time.LocalDate;
/*
* Code example to Get Year from Current local date in Java
*/
public class JExercise {
public static void main(String[] args) {
// Current Date
LocalDate localDate = LocalDate.now();
System.out.println("Date: "+localDate);
// Get Year
int year = localDate.getYear();
System.out.println("Year: "+year);
}
}
Output:
Date: 2021-02-22
Year: 2021