Search code examples
javajava-timejava.util.datejava.util.calendarjava.time.instant

Enter the year and the number of weeks, return the corresponding Monday start time,


The code looks like this:

LocalDate.of(year,1,1).with(WeekFields.of(Locale.ENGLISH).weekOfWeekBasedYear(),weekNumber).with(DayOfWeek.MONDAY)

But when I count 49 weeks for this year, which is 2023, time always returns to 2023-11-27, and I actually think it should return 2023-12-04.

I was very confused and therefore I did a lot of tests

Finally, I let the program output the first week of the year,

When I use LocalDate.of(2023, 1, 1), the output is 2022-12-26 But When I use LocalDate.of(2023, 1, 2), the output is 2023-12-04

I began to understand the design. For this reason, I had to use java.util.Calendar for this function

My question is is there a better way to solve this problem?


Solution

  • As per the documentation of weekOfWeekBasedYear:

    Week one(1) is the week starting on the getFirstDayOfWeek() where there are at least getMinimalDaysInFirstWeek() days in the year. If the first week starts after the start of the year then the period before is in the last week of the previous year. For example: - if the 1st day of the year is a Monday, week one starts on the 1st - if the 2nd day of the year is a Monday, week one starts on the 2nd and the 1st is in the last week of the previous year

    If you put the year as LocalDate.of(2023,1,1) it counts it as the last week of last year since the first day of this year is a sunday (not monday)