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

后端 未结 22 1513
余生分开走
余生分开走 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:45

    Here is my method for getting dates between two dates, including / w.o. including business days. It also takes source and desired date format as parameter.

    public static List<String> getAllDatesBetweenTwoDates(String stdate,String enddate,String givenformat,String resultformat,boolean onlybunessdays) throws ParseException{
            DateFormat sdf;
            DateFormat sdf1;
            List<Date> dates = new ArrayList<Date>();
            List<String> dateList = new ArrayList<String>();
              SimpleDateFormat checkformat = new SimpleDateFormat(resultformat); 
              checkformat.applyPattern("EEE");  // to get Day of week
            try{
                sdf = new SimpleDateFormat(givenformat);
                sdf1 = new SimpleDateFormat(resultformat);
                stdate=sdf1.format(sdf.parse(stdate));
                enddate=sdf1.format(sdf.parse(enddate));
    
                Date  startDate = (Date)sdf1.parse( stdate); 
                Date  endDate = (Date)sdf1.parse( enddate);
                long interval = 24*1000 * 60 * 60; // 1 hour in millis
                long endTime =endDate.getTime() ; // create your endtime here, possibly using Calendar or Date
                long curTime = startDate.getTime();
                while (curTime <= endTime) {
                    dates.add(new Date(curTime));
                    curTime += interval;
                }
                for(int i=0;i<dates.size();i++){
                    Date lDate =(Date)dates.get(i);
                    String ds = sdf1.format(lDate);   
                    if(onlybunessdays){
                        String day= checkformat.format(lDate); 
                        if(!day.equalsIgnoreCase("Sat") && !day.equalsIgnoreCase("Sun")){
                              dateList.add(ds);
                        }
                    }else{
                          dateList.add(ds);
                    }
    
                    //System.out.println(" Date is ..." + ds);
    
                }
    
    
            }catch(ParseException e){
                e.printStackTrace();
                throw e;
            }finally{
                sdf=null;
                sdf1=null;
            }
            return dateList;
        }
    

    And the method call would be like :

    public static void main(String aregs[]) throws Exception {
            System.out.println(getAllDatesBetweenTwoDates("2015/09/27","2015/10/05","yyyy/MM/dd","dd-MM-yyyy",false));
        }
    

    You can find the demo code : Click Here

    0 讨论(0)
  • 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;
        }
    
    
    0 讨论(0)
  • 2020-11-22 13:46

    java9 features you can calculate like this

    public  List<LocalDate> getDatesBetween (
     LocalDate startDate, LocalDate endDate) {
    
       return startDate.datesUntil(endDate)
         .collect(Collectors.toList());
    }
    `` 
    
    
    
    0 讨论(0)
  • 2020-11-22 13:47

    With Joda-Time , maybe it's better:

    LocalDate dateStart = new LocalDate("2012-01-15");
    LocalDate dateEnd = new LocalDate("2012-05-23");
    // day by day:
    while(dateStart.isBefore(dateEnd)){
        System.out.println(dateStart);
        dateStart = dateStart.plusDays(1);
    }
    

    It's my solution.... very easy :)

    0 讨论(0)
  • 2020-11-22 13:47

    This is simple solution for get a list of dates

    import java.io.*;
    import java.util.*;
    import java.text.SimpleDateFormat;  
    public class DateList
    {
    
    public static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    
     public static void main (String[] args) throws java.lang.Exception
     {
    
        Date dt = new Date();
        System.out.println(dt);
    
            List<Date> dates = getDates("2017-01-01",dateFormat.format(new Date()));
            //IF you don't want to reverse then remove Collections.reverse(dates);
             Collections.reverse(dates);
            System.out.println(dates.size());
        for(Date date:dates)
        {
            System.out.println(date);
        }
     }
     public static List<Date> getDates(String fromDate, String toDate)
     {
        ArrayList<Date> dates = new ArrayList<Date>();
    
        try {
    
            Calendar fromCal = Calendar.getInstance();
            fromCal.setTime(dateFormat .parse(fromDate));
    
            Calendar toCal = Calendar.getInstance();
            toCal.setTime(dateFormat .parse(toDate));
    
            while(!fromCal.after(toCal))
            {
                dates.add(fromCal.getTime());
                fromCal.add(Calendar.DATE, 1);
            }
    
    
        } catch (Exception e) {
            System.out.println(e);
        }
        return dates;
     }
    }
    
    0 讨论(0)
  • 2020-11-22 13:49

    This will add all dates between two dates and It will add current dates and then new dates will be added based on loop condition.

    private void onDateSet(){
        Calendar endDate = Calendar.getInstance(),startDate = Calendar.getInstance();
        startDate.set(currentYear,currentMonthOfYear,currentDayOfMonth);
        endDate.set(inputYear,inputMonthOfYear,inputDayOfMonth);
        datesToAdd(startDate,endDate);
        }
    
        //call for get dates list
        private List<Date> datesToAdd(Calendar startDate,Calendar endDate){
                        List<Dates> datesLists = new List<>();
                        while (startDate.get(Calendar.YEAR) != endDate.get(Calendar.YEAR) ||   
                               startDate.get(Calendar.MONTH) != endDate.get(Calendar.MONTH) ||
                               startDate.get(Calendar.DAY_OF_MONTH) != endDate.get(Calendar.DAY_OF_MONTH)) {
    
                                 datesList.add(new Date(startDate.get(Calendar.YEAR), startDate.get(Calendar.MONTH), startDate.get(Calendar.DATE));
    
                                 startDate.add(Calendar.DATE, 1);//increas dates
    
                             }
                             return datesList;
                    }
    
    0 讨论(0)
提交回复
热议问题