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

后端 未结 22 1540
余生分开走
余生分开走 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: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 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 getDates(String fromDate, String toDate)
     {
        ArrayList dates = new ArrayList();
    
        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;
     }
    }
    

提交回复
热议问题