Sometimes we need to find the day of the year in the current date or on some specified date.
In that case, Java provides a method getDayofYear() that returns the numbers of days passed in the year. Let's see some interesting examples.
We can use it to calculate the number of days passed in the current year. It returns an integer result that represents the days of the year in Java.
import java.time.LocalDate;
/*
* Code example to Get Day of Year from 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 Day of Year
int year = localDate.getDayOfYear();
System.out.println("Year: "+year);
}
}
Output:
Date: 2021-02-22
Year: 53
In case, we have a date string and want to get the number of days of the year then use this example.
import java.time.LocalDate;
/*
* Code example to Get Day of Year from local date in Java
*/
public class JExercise {
public static void main(String[] args) {
// Some Date
String date = "2015-08-10";
LocalDate localDate = LocalDate.parse(date);
System.out.println("Date: "+localDate);
// Get Day of Year
int year = localDate.getDayOfYear();
System.out.println("Year: "+year);
}
}
Output:
Date: 2015-08-10
Year: 222