how to get a list of dates between two dates in java

后端 未结 22 1538
余生分开走
余生分开走 2020-11-22 13:24

I want a list of dates between start date and end date.

The result should be a list of all dates including the start and end date.

22条回答
  •  心在旅途
    2020-11-22 13:46

    Enhancing one of the above solutions. As adding 1 day to end date sometimes adds an extra day beyond the end date.

    
        public static List getDaysBetweenDates(Date startdate, Date enddate)
        {
            List dates = new ArrayList();
            Calendar startDay = new GregorianCalendar();
            calendar.setTime(startdate);
            Calendar endDay = new GregorianCalendar();
            endDay.setTime(enddate);
            endDay.add(Calendar.DAY_OF_YEAR, 1);
            endDay.set(Calendar.HOUR_OF_DAY, 0);
            endDay.set(Calendar.MINUTE, 0);
            endDay.set(Calendar.SECOND, 0);
            endDay.set(Calendar.MILLISECOND, 0);
    
            while (calendar.getTime().before(endDay.getTime())) {
                Date result = startDay.getTime();
                dates.add(result);
                startDay.add(Calendar.DATE, 1);
            }
            return dates;
        }
    
    

提交回复
热议问题