We will cover examples for both older Java Date class as well as the preferred new Java Date Time API LocalDate class.
Example: Java Date Class (before Java 8)
package org.code2care.examples;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Example {
public static void main(String... args) {
Date date = new Date();
SimpleDateFormat sdfForYear = new SimpleDateFormat("yyyy");
String year = sdfForYear.format(date);
System.out.println("Year from date: " + date + " is " + year);
}
}
Output:
Example: Using LocalDate (Java 8 or above)
package org.code2care.examples;
import java.time.LocalDate;
public class Example {
public static void main(String... args) {
LocalDate localDate = LocalDate.now();
int year = localDate.getYear();
System.out.println("Year from date: " + localDate + " is " + year);
}
}
Output:

Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!