Week numbers from start date to end date Java

淺唱寂寞╮ 提交于 2019-12-08 04:46:17

问题


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"

The current week number is 34.

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


回答1:


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

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]

Note that you get both week numbers from both years, weeks of 2018 [34-52], then weeks of 2019 [1-33]




回答2:


The Answer by YCF_L is correct.

YearWeek

You may want to add the ThreeTen-Extra library to your project to make use of its YearWeek class. This class represents a specific week using the standard ISO 8601 definition of a week: starts on a Monday, week # 1 contains the first Thursday of the calendar-year, the last few ending/beginning days of the calendar-year may land in the next/previous week-based-year.

YearWeek ywStart = YearWeek.from( startDate ) ;

Increment as shown in the other Answer, but collecting YearWeek objects rather than integer numbers.

ArrayList< YearWeek > yearWeeks = new ArrayList<>( countOfWeeks + 2 ) ;  // Add one or two for good measure. 
…
YearWeek yw = yw.plusWeeks( 1 ) ;
yearWeeks.add( yw ) ;

To report, call the YearWeek::toString method to generate text in standard ISO 8601 format: yyyy-Www such as 2018-W43.



来源:https://stackoverflow.com/questions/52006506/week-numbers-from-start-date-to-end-date-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!