Reputation: 33
I am using this method to get the number of weak in a year but in my computer for the year 2020 it returns 53 but in the server it returns 52 !! I have no idea why?
Integer getNumberOfWeeksInYear(@PathParam("year") int year) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
return calendar.getWeeksInWeekYear();
}
Upvotes: 0
Views: 100
Reputation: 86306
Both answers — 52 weeks and 53 weeks — are correct. In different locales, that is.
Year 2020, a leap year, begins on a Wednesday and ends on a Thursday. Different locales count weeks in different ways. For example:
A couple of more points to note:
Calendar
class that you were using is poorly designed and long outdated.Calendar.getInstance
gives you an instance of concrete subclass of Calendar
based on default locale. It is not guaranteed to give you a Calendar
that supports getWeeksInWeekYear()
at all, so your code may crash.A correct and modern way to get the count of weeks of a week year is:
WeekFields wf = WeekFields.of(Locale.forLanguageTag("ar-TN"));
int weekYear = 2020;
// The number of weeks is the same as the week number of the last week in the week year.
// So find a date in that last week and query its week number.
// The way to find a date in the last week is:
// find a date in week 1 of the following year and subtract 1 week.
LocalDate aDateInWeek1OfTheFollowingYear = LocalDate.of(weekYear + 1, Month.FEBRUARY, 1)
.with(wf.weekOfYear(), 1);
LocalDate aDateInLastWeek = aDateInWeek1OfTheFollowingYear.minusWeeks(1);
int lastWeekNumber = aDateInLastWeek.get(wf.weekOfYear());
System.out.format("Week year %d has %d weeks.%n", weekYear, lastWeekNumber);
Output from this snippet is:
Week year 2020 has 52 weeks.
Upvotes: 1