LocalDate withDayOfYear() method in Java with Examples
The withDayOfYear() method of LocalDate class in Java returns a copy of this LocalDate with the day-of-year altered.
Syntax:
public LocalDate withDayOfYear(int dayOfYear)
Parameter: This method accepts a mandatory parameter dayOfYear which specifies the day-of-year to set in the result, from 1 to 365-366.
Returns: The function returns a LocalDate based on this date with the requested day, not null.
Exceptions: The function throws a DateTimeException when the day-of-year value is invalid.
Below programs illustrate the LocalDate.withDayOfYear() method:
Program 1:
// Program to illustrate the withDayOfYear() method import java.util.*; import java.time.*; public class GfG { public static void main(String[] args) { // Parses the date LocalDate dt1 = LocalDate.parse("2018-12-07"); LocalDate result = dt1.withDayOfYear(01); // Prints the date with year System.out.println("The date with day of year is: " + result); } } |
The date with day of year is: 2018-01-01
Program 2:
// Program to illustrate the withDayOfYear() method // Exceptions import java.util.*; import java.time.*; import java.time.temporal.ChronoField; public class GfG { public static void main(String[] args) { try { // Parses the date LocalDate dt1 = LocalDate.parse("2018-12-07"); LocalDate result = dt1.withDayOfYear(370); // Prints the date with year System.out.println("The date with month is: " + result); } catch (Exception e) { System.out.println(e); } } } |
java.time.DateTimeException: Invalid value for DayOfYear (valid values 1 - 365/366): 370
Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#withDayOfYear(int)
Recommended Posts:
- OffsetDateTime withDayOfYear() method in Java with examples
- ZonedDateTime withDayOfYear() method in Java with Examples
- LocalDateTime withDayOfYear() method in Java with Examples
- LocalDate plus() method in Java with Examples
- LocalDate get() method in Java with Examples
- LocalDate now() Method in Java with Examples
- LocalDate with() Method in Java with Examples
- LocalDate now() Method in Java with Examples
- LocalDate hashCode() method in Java with Examples
- LocalDate getYear() method in Java with Examples
- LocalDate isBefore() method in Java with Examples
- LocalDate isEqual() method in Java with Examples
- LocalDate isAfter() method in Java with Examples
- LocalDate lengthOfMonth() method in Java with Examples
- LocalDate withMonth() method in Java with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



