fatma pico
fatma pico

Reputation: 33

Calendar.getWeeksInWeekYear return diffrent values for same year but in diffrent system

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

Answers (1)

Anonymous
Anonymous

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:

  • In Tunisia (ar-TN locale) weeks begin on Saturday and the first week in a year is the week that contains January 1. So week 1 is from Saturday 28 December 2019 through Friday January 4, 2020. Week 52 is from 21 through 27 December. The week beginning 28 December is considered week 1 of 2021. So there are 52 weeks in the week year 2020.
  • In the ISO calendar system, the international standard, weeks begin on Monday and week 1 is the first week that contains at least 4 days of the new year. So week 1 is from Monday 30 December 2019 through Sunday January 5. Week 53 is from 28 December through Sunday 3 January 2021. So there are 53 weeks.

A couple of more points to note:

  • The Calendar class that you were using is poorly designed and long outdated.
  • Your code will work incorrectly in a couple of corner cases.
    • 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.
    • If you run your code on a day near New Year belonging to a week of the previous or the next year, you will get the week count of that previous or next year, not the year you queried.

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

Related Questions