71. Converting week/year to Date
Let’s consider the year 2023, week 10. The corresponding date is Sun Mar 05 15:15:08 EET 2023 (of course, the time component is relative). Converting the year/week to java.util.Date
can be done via the Calendar
API as in the following self-explanatory snippet of code:
public static Date from(int year, int week) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.WEEK_OF_YEAR, week);
calendar.set(Calendar.DAY_OF_WEEK, 1);
return calendar.getTime();
}
If you prefer to obtain a LocalDate
instead of a Date
then you can easily perform the corresponding conversion or you can rely on java.time.temporal.WeekFields
. This API exposes several fields for working with week-of-year, week-of-month, and day-of-week. This being said, here is the previous solution written via WeekFields
to return a LocalDate
:
public static LocalDate from(int year, int week) {
WeekFields weekFields = WeekFields...