To get the year from the date-time in Java, you can use the getYear() method of the LocalDateTime class.
This method was added to Java 8 date-time API. So, can be used in Java 8 and higher versions such as Java 11, Java 17, etc.
The getYear() method returns the year field from the date-time. For example, if we want to get year from the "2022-03-14T17:12:17", then the result will be "2002".
Let's understand with the running examples
Here, we first used the parse() method to create a date-time object and then used the getYear() method to get year.
/*
* Code example to get year from date in Java
*/
import java.time.LocalDateTime;
public class JExercise {
public static void main(String[] args) {
// String date is given
String strDate = "2022-03-14T17:12:17";
// parse the string date into date time
LocalDateTime date = LocalDateTime.parse(strDate);
// Displaying date and time
System.out.println("Date : "+date);
// Get year from the date
int year = date.getYear();
// Display result
System.out.println("Year : "+year);
}
}
Output:
Date : 2022-03-14T17:12:17
Year : 2022
In the above code, we first parsed the String date to LocalDateTime object by using the parse() method.
If you already have LocalDateTime object, then you don't need to parse it.
You can directly call the getYear() method.
Now, let's have a look at this method signature:
public int getYear()
Package Name: java.time;
Class Name: LocalDateTime
Return Value: It returns an int value that represents the year from MIN_YEAR to MAX_YEAR.
Parameters: It does not take any parameters.
Exceptions: It does not throw any exception.
Version: Since 1.8
If you want to get the year from the current date then use the below code.
Here, we first call the now() method to get the current date-time and then used the getYear() to get the year.
/*
* Code example to get year from date in Java
*/
import java.time.LocalDateTime;
public class JExercise {
public static void main(String[] args) {
// Take current date and time
LocalDateTime date = LocalDateTime.now();
// Displaying date and time
System.out.println("Date : "+date);
// Get year from the date
int year = date.getYear();
// Display result
System.out.println("Year : "+year);
}
}
Output:
Date : 2022-03-14T21:43:32.027795952
Year : 2022
Use this code to get results in a single line of code. If you are a beginner, skip this code.
LocalDateTime.now().getYear();
This code will return an int value that represents the current year of the current date-time. You just copy this code the result instantly.