generate dates between two date in Android

后端 未结 2 1194
面向向阳花
面向向阳花 2021-02-20 17:38

How to get all dates between two dates in Android.

For example. I have two Strings.

String first=\"2012-07-15\";  
String second=\"2012-07-21\"; 
         


        
2条回答
  •  死守一世寂寞
    2021-02-20 18:27

    it is better not to use any hardcoded values in date calculations. we can rely on java Calendar class methods to do this task

    see the code

    private static List getDates(String dateString1, String dateString2)
    {
        ArrayList dates = new ArrayList();
        DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
    
        Date date1 = null;
        Date date2 = null;
    
        try {
            date1 = df1 .parse(dateString1);
            date2 = df1 .parse(dateString2);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
    
    
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
    
        while(!cal1.after(cal2))
        {
            dates.add(cal1.getTime());
            cal1.add(Calendar.DATE, 1);
        }
        return dates;
    }
    

    and use it as below

        List dates = getDates("2012-02-01", "2012-03-01");
        for(Date date:dates)
            System.out.println(date);
    

提交回复
热议问题