Introduction
In this lab, we will learn how to use the withDayOfYear()
method in Java LocalDate
class to create a date with a new day-of-year value.
In this lab, we will learn how to use the withDayOfYear()
method in Java LocalDate
class to create a date with a new day-of-year value.
Create a file LocalDateWithDayOfYear.java
under the ~/project
directory with the following code:
import java.time.LocalDate;
public class LocalDateWithDayOfYear {
public static void main(String[] args) {
System.out.println("Original date: ");
LocalDate localDate = LocalDate.of(2002, 01, 10);
System.out.println(localDate);
}
}
Use the following command to compile and run the code:
javac LocalDateWithDayOfYear.java && java LocalDateWithDayOfYear
The output should show the original date:
Original date:
2002-01-10
To create a new date by setting a new value of a day-of-year, we can use the withDayOfYear()
method to set a new day for the date.
Add the following code after the System.out.println(localDate);
line:
// set day-of-year as 30
localDate = localDate.withDayOfYear(30);
System.out.println("New date with day-of-year set as 30: ");
System.out.println(localDate);
// set day-of-year as 300
localDate = localDate.withDayOfYear(300);
System.out.println("New date with day-of-year set as 300: ");
System.out.println(localDate);
Use the following command to compile and run the code:
javac LocalDateWithDayOfYear.java && java LocalDateWithDayOfYear
The output should show the new dates with the new day-of-year values:
Original date:
2002-01-10
New date with day-of-year set as 30:
2002-01-30
New date with day-of-year set as 300:
2002-10-27
If the resulting date is invalid, an exception will be thrown. We can handle the exception using try-catch block as follows:
try {
// set day-of-year as 366 (invalid for non-leap year)
localDate = localDate.withDayOfYear(366);
System.out.println(localDate);
} catch (Exception e) {
System.out.println("Invalid date: " + e.getMessage());
}
Use the following command to compile and run the code:
javac LocalDateWithDayOfYear.java && java LocalDateWithDayOfYear
The output should show the message of invalid date exception:
Original date:
2002-01-10
New date with day-of-year set as 30:
2002-01-30
New date with day-of-year set as 300:
2002-10-27
Invalid date: Invalid date 'DayOfYear 366' as '2002' is not a leap year
In this lab, we have learned how to use the withDayOfYear()
method in Java LocalDate
class to create a date with a new day-of-year value. We have also learned how to handle the invalid date exception when setting a new day-of-year value.