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

后端 未结 22 1964
余生分开走
余生分开走 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 getAllDatesBetweenTwoDates(String stdate,String enddate,String givenformat,String resultformat,boolean onlybunessdays) throws ParseException{
            DateFormat sdf;
            DateFormat sdf1;
            List dates = new ArrayList();
            List dateList = new ArrayList();
              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

    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

提交回复
热议问题