从开始日期到结束日期的周数Java
我试图获取介于Java中给定开始日期和结束日期之间的星期数.这是 ISO8601
日期.
I trying to get the week numbers which fall between a given start date and end date in Java. This is ISO8601
date.
Example
startDate - "2018-08-24T12:18:06,166"
endDate - "2019-08-24T11:18:06,166"
当前星期数是34.
对于此示例,我将得到34,35,36 ... 2018年的上周数..1,2 ... 2019年的上周数,依此类推
For this example, I would get 34,35,36... Last week number of 2018..1,2...last week number of 2019 and so on
对此有一个好的解决方案吗?
Is there a good solution to this ?
目前,我可以在相同的年份日期范围内使用它,我尝试的是,我从开始日期和结束日期获取开始周编号和结束周编号,然后循环给出开始值和结束值.但是,如果日期范围是多年,它将如何?谁能帮助我
Presently I got it worked with same year date range, what I tried is, I get the start week number and end week number from the start date and end date, and then I loop it giving the start value and end value. But if the date range falls in multiple years, how would it be? Can any one help me
If you are using Java 8 you can use java.time API Like so :
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);
}
[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]
Note that you get both week numbers from both years, weeks of 2018 [34-52]
, then weeks of 2019 [1-33]