Java时间:获取特定年份的最大周数 [英] Java Time: Get max number of weeks for particular year

查看:472
本文介绍了Java时间:获取特定年份的最大周数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只找到了 Joda时间的解决方案.

仅当最后一天不在第一周时,我的解决方案才有效:

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

那么Java时间(例如Joda Time)中的正确方法是什么?

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

推荐答案

此信息可直接通过java.time.* API获得.

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

关键方法是 rangeRefinedBy(Temporal) .它使您可以获取ValueRange对象,该对象提供字段的最小值和最大值,并由传入的临时对象完善.

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.

要了解一年中有多少ISO周,请执行以下操作:

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

请注意,您传递的日期用于确定答案.因此,在传递1月初或12月下旬的日期时,请确保您了解基于ISO周的日历的工作原理,以及日历年与基于周的年之间的差异.

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.

这篇关于Java时间:获取特定年份的最大周数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆