To get the total days of any year, you can use the lenghtOfYear() method of the LocalDate class in Java.
The length of a year or total days in a year is the count of total days of the year.
For example, the length of the year 2020 is 366 which means it has 366 days. The length of a year varies based on the leap and non-leap years.
Let's see some running examples.
In the below example, we have a string date. So, first, we parsed it to the LocalDate object and then used the lengthOfYear() method to get the total days.
/*
* Code example to find length of year of the local date in Java
*/
import java.time.LocalDate;
public class JExercise {
public static void main(String[] args) {
// String date is given
String strDate = "2020-02-14";
// parse the string date into locale date
LocalDate date = LocalDate.parse(strDate);
// Getting the length of year
int length = date.lengthOfYear();
System.out.println("Length of Year = "+length);
}
}
Output:
Length of Year = 366
Now, let's see the method signature:
public int lengthOfYear()
Package Name: java.time;
Class Name: It belongs to the LocalDate class.
Return Value: It returns the length of the year in days.
Parameters: It does not take any parameters.
Version: Since 1.8
Let's see some more examples.
To find the total days in the current year, you first need to use the now() method of the LocalDate class to get the current date.
After that use the lengthOfYear() method to get the total days of the current year. See the below Java code.
/*
* Code example to find length of year of the local date in Java
*/
import java.time.LocalDate;
public class JExercise {
public static void main(String[] args) {
// Current date
LocalDate date = LocalDate.now();
// Getting the length of year
int length = date.lengthOfYear();
System.out.println("Length of Year = "+length);
}
}
Output:
Length of Year = 365