Java Time: Get max number of weeks for particular year

后端 未结 4 963

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
  .         


        
4条回答
  •  北海茫月
    2020-12-21 09:09

    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.

提交回复
热议问题