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

I know what Calendar.WEEK_OF_YEARcould be used to get the "week of the year" on a specific date, but how do I get the appropriate YEAR ?.

I know that the definition of the Week of the Year depends on . And I'm mostly interested in the DIN 1355-1 / ISO 8601 / German solution standard (but I don't want this to be a fix), Locale

So it may happen that January 1 belongs to:

  • The first week of the year (1) of the new year: for example, 2015-01-01 - in the week of year 1 of 2015.
  • last week of the year (53) of the year before: for example, 2016-01-01 - per week of the year 53 years of 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 decision not to: date.getYear, date.getFirstDayOfWeek.getYearordate.getLastDayOfWeek.getYear

+4
2

calendar.getWeekYear(); 2015 .

. API GregorianCalendar # getWeekYear(), .

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);

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

java.time

java.time, Java 8 . java.util.Date/.Calendar.

java.time LocalDate . , , ", ".

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

IsoFields ISO 8601, .

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

/ ± 1, . , ISO 8601 2015 : 52 1 52 53.

enter image description here

enter image description here

+1

Source: https://habr.com/ru/post/1623815/


All Articles