LAST UPDATED: NOVEMBER 27, 2020
Java LocalDate withDayOfYear() Method
Java withDayOfYear() method is used to get a date with the new day-of-year. It returns a copy of this LocalDate
with the day-of-year altered. For example, we have a date 2015-01-14 then setting day-of-year as 20 will result in 2015-01-20.
If the resulting date is invalid, an exception is thrown.
It takes an argument of int type. The syntax of the method is given.
Syntax
public LocalDate withDayOfYear(int dayOfYear)
Parameters:
dayOfYear - the day-of-year to set in the resulted date.
Returns:
Returns a LocalDate based on this date with the requested day.
Time for an Example:
Let's take an example to create a new date by setting a new value of a day-of-year. Here, we are using withDayOfYear()
method to set a new day for the date.
import java.time.LocalDate;
public class DateDemo {
public static void main(String[] args){
LocalDate localDate = LocalDate.of(2002, 01, 10);
System.out.println(localDate);
localDate = localDate.withDayOfYear(30);
System.out.println("New Date : "+localDate);
}
}
2002-01-10
New Date : 2002-01-30
Time for another Example:
Let's take another example to understand the withDayOfYear()
method. Here, we are setting day-of-year as 300 and getting a new date.
import java.time.LocalDate;
public class DateDemo {
public static void main(String[] args){
LocalDate localDate = LocalDate.of(2002, 01, 10);
System.out.println(localDate);
localDate = localDate.withDayOfYear(300);
System.out.println("New Date : "+localDate);
}
}
2002-01-10
New Date : 2002-10-27
Live Example:
Try with a live example, execute the code instantly with our powerful Online Java Compiler.