Search code examples
javadatecalendarlocaleweek-number

How to get the YEAR for week of year for a date?


I know that Calendar.WEEK_OF_YEAR could been used to obtain the "week of year" for a given date, but how do I get the corresponding YEAR?.

I know that the definition of Week of Year is dependent on Locale. And I am mostly interested in a DIN 1355-1 / ISO 8601 / German solution (but I do not want to make it a fix implementation).

So it could happen that the 1 January belongs to:

  • the first week of year (1) of the new year: for example 2015-01-01 is in week of year 1 of 2015
  • the last week of year (53) of the year before: for example 2016-01-01 is in week of year 53 of year 2015

My question is how to get this year?*

Date date =
Calender calendar = new GregorianCalendar(Locale.GERMAN)
calendar.setTime(date);

int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
int year       = ????                                             <------------

System.out.println(date + " is in " + weekOfYear + " of " + year);

* the solution is not: date.getYear, date.getFirstDayOfWeek.getYear or date.getLastDayOfWeek.getYear


Solution

  • Java 8 or later?

    Refer to Basil Bourque's answer to use Java's java.time API.

    Otherwise (think twice!) see my original answer to use the obsolete Java API as asked in this question.


    Pre Java 8?

    calendar.getWeekYear(); returns 2015 for your given example.

    See API documentation for GregorianCalendar#getWeekYear() as well as week year.

    For reference

    Calendar calendar = new GregorianCalendar(Locale.GERMAN);
    calendar.set(2016, Calendar.JANUARY, 1, 0, 0, 0);
    Date date = calendar.getTime();
    
    int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
    int year       = calendar.getWeekYear();
    
    System.out.println(date + " is in " + weekOfYear + " of " + year);
    

    returns

    Fri Jan 01 00:00:00 CET 2016 is in 53 of 2015