在JodaTime中,有没有一种方法可以轻松确定哪个星期属于哪个月?
给定月份数字的东西会返回与之关联的一年中的星期。如果一周中有4+天属于一周,则应将一周与特定的月份联系起来。
In 2014 for month = 1 then weeks = [1, 2, 3, 4, 5] (note 5 weeks because of 4 days rule)
In 2014 for month = 3 then weeks = [10, 11, 12, 13] (note 4 weeks because of same rule)
我不想“手动”计算...
最佳答案
您必须实例化 DateTime
对象以获得指定的星期数,然后才读取其month property(使用Joda-Time和Google Guava)。
DateTime dateTime = new DateTime().withWeekOfWeekyear(i).withDayOfWeek(DateTimeConstants.MONDAY);
if (dateTime.dayOfMonth().getMaximumValue() - dateTime.dayOfMonth().get() < 3) {
dateTime = dateTime.plusMonths(1);
}
int month = dateTime.monthOfYear().get();
我们还可以使用下面的功能来打印所有月份,并把它们归为几周:
public static void main(String[] args) {
Multimap<Integer, Integer> monthsWithWeeks = LinkedListMultimap.create();
int weeksInYear = new DateTime().withYear(2014).weekOfWeekyear().getMaximumValue();
for (int i = 1; i <= weeksInYear; i++) {
DateTime weekDate = new DateTime().withWeekOfWeekyear(i).withDayOfWeek(DateTimeConstants.MONDAY);
if (weekDate.dayOfMonth().getMaximumValue() - weekDate.dayOfMonth().get() < 3) {
weekDate = weekDate.plusMonths(1);
}
int month = weekDate.monthOfYear().get();
monthsWithWeeks.put(month, i);
}
for (Integer month : monthsWithWeeks.keySet()) {
System.out.println(String.format("%d => [%s]", month, Joiner.on(',').join(monthsWithWeeks.get(month))));
}
}