'Java - Getting same day of week for next year
I was looking for a way to make optimum of Java 8's LocalDate to find next year's date which falls on same day of week.
For example today is 1rd March 2022 - Tuesday. Assume this is the input date, the the output date that I expect to get is 28th Feb 2023, because its the same day (Tuesday) for next year
One option that I tried was adding 364 days as shown in the example
public static void main(String args[]){
LocalDate currentDate= LocalDate.now();
System.out.println("Current Date: " + currentDate + " Day" currentDate.getDayOfWeek().name());
System.out.println("Next Year's date: " + currentDate.plusDays(364) + " Next year day: " +currentDate.plusDays(364).getDayOfWeek().name());
}
This works but may have drawback with leap years.
Other option is to add 1 year to current date and do a while loop check for dayOfWeek for each day - 1
Is there a better way to do this?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
