15

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.

Akhila
  • 3,235
  • 1
  • 14
  • 30
Hardik Joshi
  • 9,477
  • 12
  • 61
  • 113
  • 3
    possible duplicate of [How can I increment a date by one day in Java?](http://stackoverflow.com/questions/428918/how-can-i-increment-a-date-by-one-day-in-java) - You can run the increment in a loop to create the date series. – assylias Jul 10 '12 at 11:53
  • Perhaps not yet available in Android, but in regular Java use [`LocalDate::datesUntil`](https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#datesUntil(java.time.LocalDate)): `LocalDate.parse( "2012-07-15" ).datesUntil( "2012-07-21" )` yields a [`Stream`](https://docs.oracle.com/javase/10/docs/api/java/util/stream/Stream.html). – Basil Bourque Nov 23 '18 at 04:58
  • For new readers to the question I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDate` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Jul 03 '21 at 09:25

5 Answers5

50

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);
sunil
  • 6,444
  • 1
  • 32
  • 44
  • `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 – Akhila Feb 07 '19 at 14:55
  • @AkhilaMadari You have to use classes `java.text.DateFormat` and `java.text.SimpleDateFormat`. Please check if you have imported classes from correct packages. – sunil Feb 08 '19 at 01:18
  • 1
    Perfect solution – Mohd Sakib Syed Nov 21 '19 at 07:13
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);


 }
}
Ram kiran Pachigolla
  • 20,897
  • 15
  • 57
  • 78
1

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
    }
Rahul Khatri
  • 1,502
  • 2
  • 13
  • 25
1

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

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
0
        val currentDateCalendar = Calendar.getInstance()
        val mCurrentDate = getDateChanger(currentDateCalendar.time, "yyyy-MM-dd")
        currentDateCalendar.add(Calendar.MONTH, 1)
        val oneMonthNextCalendar = currentDateCalendar
        val mNextDate = getDateChanger(oneMonthNextCalendar.time, "yyyy-MM-dd")

        val mDates = datesBetween(
            mCurrentDate,
            mNextDate,
            "yyyy-MM-dd"
        )
        for (date in mDates)
            Log.i("DatesBetween",date)





 @SuppressLint("SimpleDateFormat")
    fun getDateChanger(mDate:Date,formatter: String): String {
        val dateFormat = SimpleDateFormat(formatter)
        return dateFormat.format(mDate)
    }

    @SuppressLint("SimpleDateFormat")
    fun datesBetween(startDate: String, endDate: String,formatter: String): List<String> {
        val dates = ArrayList<String>()
        val dateFormat: DateFormat = SimpleDateFormat(formatter)
        var sDate: Date? = null
        var eDate: Date? = null
        try {
            sDate = dateFormat.parse(startDate)
            eDate = dateFormat.parse(endDate)
        } catch (e: ParseException) {
            e.printStackTrace()
        }
        val sCalendarDate = Calendar.getInstance()
        sCalendarDate.time = sDate!!
        val eCalendarDate = Calendar.getInstance()
        eCalendarDate.time = eDate!!
        while (!sCalendarDate.after(eCalendarDate)) {
            dates.add(dateFormat.format(sCalendarDate.time))
            sCalendarDate.add(Calendar.DATE, 1)
        }
        return dates
    }
Yaqoob Bhatti
  • 1,271
  • 3
  • 14
  • 30