Using the https://www.threeten.org/threeten-extra library.
When computing the first Sunday of the month, given week number and year, I noticed that if I used 2018 and week 53, I get as the result the first Sunday 2018-12-02.
Yet, 2018 is not a 53-week year so I am wondering if I'm doing something wrong or perhaps there's something special about 2018? I didn't see that the week start date or other 53-week conditions were met, but I could have missed something.
In other tests like 2011 (also not a and week 53-week year), the date logic wraps the result as expected to 2012-01-01 (the first Sunday in the first week of the next year).
Years 2020, 2015, and 2019 (all 53-week years) display the result value as expected in December of the respective year.
Here is the code:
YearWeek yw = YearWeek.of(year, weekNumber);
//Get the date of the first day of that week.
LocalDate ld = yw.atDay( DayOfWeek.MONDAY ) ;
// Use a TemporalAdjuster to get nth day-of-week of that month date’s month.
TemporalAdjuster ta = TemporalAdjusters.dayOfWeekInMonth( 1 , DayOfWeek.SUNDAY ) ;
// TemporalAdjuster ta = TemporalAdjusters.firstDayOfMonth();
LocalDate firstSunday = ld.with( ta ) ;
return firstSunday.toString();
Suggestions?
CodePudding user response:
This is what YearWeek.of
does:
Obtains an instance of YearWeek from a week-based-year and week.
If the week is 53 and the year does not have 53 weeks, week one of the following year is selected.
Therefore, for (2018, 53)
, it selects the first week of 2019, because 2018 only has 52 weeks. This is the week starting from 2018-12-31 and ending at 2019-01-06.
You then get the Monday of this week, which is 2018-12-31, and adjusts this date to the first Sunday of the month. "The month" here being December, you get 2018-12-02 as a result.
Similarly, for (2011, 53)
, you get the first week of 2012 because 2011 only has 52 weeks. But unlike 2019, this is the week starting from 2012-01-02 and ending at 2012-01-08, so there is no problem.
So what's "special" about 2018? Its last week ends before the last day of the year, I suppose? This causes the first week of the next year to start in December.