generate dates between two date in Android

13,131

Solution 1

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<Date> getDates(String dateString1, String dateString2)
{
    ArrayList<Date> dates = new ArrayList<Date>();
    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<Date> dates = getDates("2012-02-01", "2012-03-01");
    for(Date date:dates)
        System.out.println(date);

Solution 2

public class DummyWorks extends Activity 
{
static final long ONE_DAY = 24 * 60 * 60 * 1000L;
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    getDatesBetween("03/23/2011","03/28/2011");
}

public static void getDatesBetween(String startDate,String endDate) {


    long  from=Date.parse(startDate);  

    long to=Date.parse(endDate);  

    int x=0;

    while(from <= to) {
          x=x+1;
          System.out.println ("Dates  : "+new Date(from));
          from += ONE_DAY;
    }
    System.out.println ("No of Dates  :"+ x);


 }
}

Solution 3

Solution in Kotlin: It will return List of Date between 2 dates.

 fun getDatesBetween(dateString1:String, dateString2:String):List<String> {
        val dates = ArrayList<String>()
        val input = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        var date1:Date? = null
        var date2:Date? = null
        try
        {
            date1 = input.parse(dateString1)
            date2 = input.parse(dateString2)
        }
        catch (e:ParseException) {
            e.printStackTrace()
        }
        val cal1 = Calendar.getInstance()
        cal1.time = date1
        val cal2 = Calendar.getInstance()
        cal2.time = date2
        while (!cal1.after(cal2))
        {
            val output = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
            dates.add(output.format(cal1.time))
            cal1.add(Calendar.DATE, 1)
        }
        return dates
    }

Solution 4

java.time through desugaring

Consider using java.time, the modern Java date and time API, for your date work. LocalDate is the class to use for a date (without time of day). I was assuming you wanted all the dates inclusive of the two given ones.

    String first = "2012-07-15";
    String second = "2012-07-21";
    
    List<LocalDate> dates = LocalDate.parse(first)
            .datesUntil(LocalDate.parse(second).plusDays(1))
            .collect(Collectors.toList());
    
    System.out.println(dates);

Output:

[2012-07-15, 2012-07-16, 2012-07-17, 2012-07-18, 2012-07-19, 2012-07-20, 2012-07-21]

LocalDate.datesUntil() gives us a stream of dates exclusive of the specified end date, so we need to add one day to it to have it included.

I am exploiting the fact that your strings are in ISO 8601 format and that LocalDate parses this format as its default, that is, without any explicit formatter.

Or through ThreeTenABP

If for some reason you are using the ThreeTenABP library rather than desugaring, I believe that the datesUntil method is not there. In this case use a loop instead.

    List<LocalDate> dates = new ArrayList<>();
    LocalDate currentDate = LocalDate.parse(first);
    LocalDate lastDate = LocalDate.parse(second);
    while (! currentDate.isAfter(lastDate )) {
        dates.add(currentDate);
        currentDate = currentDate.plusDays(1);
    }

[2012-07-15, 2012-07-16, 2012-07-17, 2012-07-18, 2012-07-19, 2012-07-20, 2012-07-21]

Question: Doesn’t java.time require Android API level 26?

java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On older Android either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Share:
13,131
Hardik Joshi
Author by

Hardik Joshi

Right now i am working as an Android Application Developer having 8+ years of experience. Contact Me: Mail: [email protected] Skype: hardik.joshi841 Proud to be INDIAN Some owsome Apps Join Me : http://androiddevelopmentworld.blogspot.in/

Updated on June 09, 2022

Comments

  • Hardik Joshi
    Hardik Joshi about 2 years

    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"; 
    

    I convert and get dates from these strings.

    DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");                                    
    DateFormat df2 = new SimpleDateFormat("MMM dd");
    String mydate = df2.format(df1.parse(first));
    

    This way I get both dates from first and second String.

    Now I also display all dates between these two dates.

  • assylias
    assylias almost 12 years
    Adding milliseconds to your date brings a high risk of failure due to daylight savings and other weird timezone changes.
  • Ram kiran Pachigolla
    Ram kiran Pachigolla almost 12 years
    thanks @assylias, now i tested it.its getting correct result after changing "long ONE_DAY"
  • Hardik Joshi
    Hardik Joshi almost 12 years
    hello @Ramkiran thanks for reply. But i got error at long from = Date.parse(startDate); which says that java.illegalArgumentException at java.util.Date.parse.
  • Hardik Joshi
    Hardik Joshi almost 12 years
    My date format is 2012-07-15. i need to format it with your date format? what i add to this function?
  • Hardik Joshi
    Hardik Joshi almost 12 years
    Yes i think thats why i get error. What is change in getDatesBetween() function?
  • Akhila Madari
    Akhila Madari over 5 years
    DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd"); this line says incompatable types for me. when I change it to SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd"); then it works for me
  • sunil
    sunil over 5 years
    @AkhilaMadari You have to use classes java.text.DateFormat and java.text.SimpleDateFormat. Please check if you have imported classes from correct packages.
  • Mohd Sakib Syed
    Mohd Sakib Syed over 4 years
    Perfect solution