gpt4 book ai didi

java - 从开始日期到结束日期的周数Java

转载 作者:行者123 更新时间:2023-11-29 06:27:08 24 4
gpt4 key购买 nike

我试图获取 Java 中给定开始日期和结束日期之间的周数。这是 ISO8601 日期。

Example 
startDate - "2018-08-24T12:18:06,166"
endDate - "2019-08-24T11:18:06,166"

当前周数是 34。

对于这个例子,我会得到 34,35,36... 2018 年的上周数..1,2...2019 年的上周数等等

有好的解决办法吗?

目前我让它在同一年的日期范围内工作,我尝试的是,我从开始日期和结束日期获取开始周数和结束周数,然后我循环它给出开始值和结束值。但如果日期范围落在多年内,会怎样?谁能帮帮我

最佳答案

如果您使用的是 Java 8,则可以使用 java.time API 像这样:

int addWeek = 0;
if(startDate.get(WeekFields.ISO.weekOfYear()) < endDate.get(WeekFields.ISO.weekOfYear())){
addWeek = 1;
}
long weeks = WEEKS.between(startDate, endDate) + addWeek;//Get the number of weeks in your case (52)
List<Integer> numberWeeks = new ArrayList<>();
if (weeks >= 0) {
int week = 0;
do {
//Get the number of week
int weekNumber = startDate.plusWeeks(week).get(WeekFields.ISO.weekOfYear());
numberWeeks.add(weekNumber);
week++;
} while (week <= weeks);
}

Ideone demo

[34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34]

请注意,您会获得这两年的周数,2018 [34-52] 的周数,然后是 2019 [1-33] 的周数>

关于java - 从开始日期到结束日期的周数Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52006506/

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