java.time and Year.atDay()
public static void startEndDate(int endDay)
{
LocalDate date = Year.of(2020).atDay(endDay);
System.out.println("For the given end day of " + endDay
+ " the date returned is : " + date);
}
Let’s try it out:
startEndDate(35);
startEndDate(49);
startEndDate(70);
Output is:
For the given end day of 35 the date returned is : 2020-02-04 For the given end day of 49 the date returned is : 2020-02-18 For the given end day of 70 the date returned is : 2020-03-10
The documentation of Year.atDay()
explains:
Combines this year with a day-of-year to create a
LocalDate
.
Please fill in your desired year where I put 2020.
I recommend you don’t use Date
. That class is poorly designed and long outdated. Instead I am using Year
and LocalDate
, both from java.time, the modern Java date and time API.
A comment suggested regarding your question as a question of adding a number of days to December 31 of the previous year. IMO regarding it as finding a date from the number of the day-of-year gives a somewhat more elegant solution.
Links
- Oracle tutorial: Date Time explaining how to use java.time.
- Documentation of
Year.atDay(int dayOfYear)
- Documentation of
LocalDate.ofYearDay()
, a good alternative
solved Converting an integer to expected Date value in java [duplicate]