Java time: get maximum number of weeks for a specific year

I found a solution for Joda Time .

My solution only works if the last day is not the first week:

LocalDate.now() // or any other LocalDate
  .withDayOfMonth(31)
  .withMonth(12)
  .get(weekFields.weekOfWeekBasedYear())

      

So what's the correct way in Java Time (like in Joda Time)?

+3


source to share


3 answers


This information is available directly through the API java.time.*

.

The key method is rangeRefinedBy(Temporal)

in TemporalField

. It allows you to get an object ValueRange

that provides the minimum and maximum values ​​for the field, as specified by the transferable object.

To find out how many ISO weeks in a year, follow these steps:



LocalDate date = LocalDate.of(2015, 6, 1);
long weeksInYear = IsoFields.WEEK_OF_WEEK_BASED_YEAR.rangeRefinedBy(date).getMaximum();
System.out.println(weeksInYear);

      

Please note that the date you pass is used to determine the response. So when traversing early January or late December dates, make sure you understand how the ISO week calendar works, as well as the difference between the calendar year and the weekly year.

+6


source


It seems that when is the last day in the first week, you don't want to receive 1

as a response, but 52/3/4

, in this case, you can search for:

LocalDate.of(2017, 12, 31).get(WeekFields.ISO.weekOfYear());

      



There are several ways to define week numbers - if that doesn't do what you want, you need to figure out which method you want to use.

0


source


The correct and best solution is given by @JodaStephen . Here are some alternatives.

December 28 is always the last week of the year, because the remaining three days later cannot make up the bulk of another week:

int weeks = LocalDate.of(2017, 12, 28).get(WeekFields.ISO.weekOfYear());

      

The year has 53 weeks if it starts or ends on Thursday:

Year year = Year.of(2017);
DayOfWeek firstDay = year.atDay(1).getDayOfWeek();
DayOfWeek lastDay = year.atDay(year.length()).getDayOfWeek();
int weeks = firstDay == DayOfWeek.THURSDAY || lastDay == DayOfWeek.THURSDAY ? 53 : 52;

      

Finally, this will give you the "week number" of the last day of the year. 53 also in cases where the last week number is 52, if the main part of the last week of the week will be in the next year (the week will be declared for the next year).

// This will not give the correct number of weeks for a given year
Year year = Year.of(2018);
year.atDay(year.length()).get(WeekFields.ISO.weekOfYear()); // 53

      

What have you actually done.

0


source







All Articles