Javaexercise.com

Updated On 2022-07-01 04:11:07

How to Get Day of Year in Java LocalDate?

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.

  • Get Day of Year Java LocalDate
  • Get the number of days passed in the specified date

Get Days of a Year from the Local Date using the getDayofYear() method in Java

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
 

Get Day of Year from the Local Date in Java

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
 

Related Articles