gpt4 book ai didi

java - 哪些周与哪些月份相关联?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:13:36 24 4
gpt4 key购买 nike

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

关于java - 哪些周与哪些月份相关联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21054984/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com