Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Time: Get max number of weeks for particular year

I only found a solution for Joda Time.

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

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

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

like image 976
pme Avatar asked Jan 21 '26 11:01

pme


2 Answers

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

The key method is rangeRefinedBy(Temporal) on TemporalField. It allows you to obtain a ValueRange object that provides the minimum and maximum values for the field, refined by the temporal object passed in.

To find out how many ISO weeks there are in the year, do the following:

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

Note that the date you pass in is used to determine the answer. So when passing in dates in early January or late December ensure you understand how the ISO week-based calendar works, and the difference between the calendar year and the week-based year.

like image 87
JodaStephen Avatar answered Jan 24 '26 01:01

JodaStephen


If one wants to get the week number based on 7 days no matter when the week starts and how many days the first partial week of the year has, ChronoField.ALIGNED_WEEK_OF_YEAR might be helpful.

For example, the 1st of January 2016 based on the ISO-8601 definition (where a week starts on Monday and the first week has a minimum of 4 days) falls into week number 0, but in the aligned it is week number 1.

    LocalDate date = LocalDate.of(2016, 1, 1);

    int iso8601 = date.get(WeekFields.ISO.weekOfYear()); // result is 0

    int aligned = date.get(ChronoField.ALIGNED_WEEK_OF_YEAR); // result is 1
like image 30
zoomout Avatar answered Jan 24 '26 01:01

zoomout



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!