4

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

Community
  • 1
  • 1
Ralph
  • 118,862
  • 56
  • 287
  • 383

2 Answers2

3

java.time

You should be using the java.time framework built into Java 8 and later. Avoid the old and notoriously troublesome java.util.Date/.Calendar classes.

These new java.time classes include LocalDate for date-only value without time-of-day or time zone. Note that you must specify a time zone to determine ‘today’ as the date is not simultaneously the same around the world.

ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime now = ZonedDateTime.now ( zoneId );

The IsoFields class provides info according to the ISO 8601 standard including the week-of-year for a week-based year.

int calendarYear = now.getYear();
int weekNumber = now.get ( IsoFields.WEEK_OF_WEEK_BASED_YEAR );
int weekYear = now.get ( IsoFields.WEEK_BASED_YEAR );  // Answer to Question

Near the beginning/ending of a year, the week-based-year may be ±1 different than the calendar-year. For example, notice the difference between the Gregorian and ISO 8601 calendars for the end of 2015: Weeks 52 & 1 become 52 & 53.

enter image description here

enter image description here

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
2

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
Ivo Mori
  • 2,177
  • 5
  • 24
  • 35