Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate between two date range using Joda

In my code I need to iterate between a range of dates using Joda, and I already tried this:

for(LocalDate currentdate = startDate; currenDate.isBefore(endDate); currenDate= currenDate.plusDays(1)){
    System.out.println(currentdate);
}

The above code is working, but the iteration stops when currenDate reaches the day before endDate. What I want to achieve is that the iteration stops when currentDate is exactly the same as endDate.

for(Date currentdate = startDate; currentdate <= endDate; currentdate++){
    System.out.println(currentdate );
}

I know the code above is impossible, but I do it to make clear what I'd want.

like image 572
Gusti Arya Avatar asked Mar 25 '15 01:03

Gusti Arya


1 Answers

Actually there's a simple way around to your original code you posted, see my implementation below, just modified your for loop implementation:

    //test data
    LocalDate startDate = LocalDate.now(); //get current date
    LocalDate endDate = startDate.plusDays(5); //add 5 days to current date

    System.out.println("startDate : " + startDate);
    System.out.println("endDate : " + endDate);

    for(LocalDate currentdate = startDate; 
            currentdate.isBefore(endDate) || currentdate.isEqual(endDate); 
            currentdate= currentdate.plusDays(1)){
        System.out.println(currentdate);
    }

Below is the Output (with respect to my localDate):

startDate : 2015-03-26
endDate : 2015-03-31
2015-03-26
2015-03-27
2015-03-28
2015-03-29
2015-03-30
2015-03-31

Hope this helps! Cheers. :)

like image 195
javaMaster Avatar answered Sep 22 '22 21:09

javaMaster