Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

date

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.

like image 452
Arivu2020 Avatar asked Apr 22 '10 08:04

Arivu2020


People also ask

How do I find the date between two dates?

Use the DATEDIF function when you want to calculate the difference between two dates. First put a start date in a cell, and an end date in another. Then type a formula like one of the following.

How do you create a date range in Java?

The idea is quite simple, just use Calendar class to roll the month back and forward to create a “date range”, and use the Date. before() and Date.

How do I extract dates between two dates in Excel?

To find the number of days between these two dates, you can enter “=B2-B1” (without the quotes into cell B3). Once you hit enter, Excel will automatically calculate the number of days between the two dates entered. Note that Excel recognizes leap years.


2 Answers

Back in 2010, I suggested to use Joda-Time for that.

Note that Joda-Time is now in maintenance mode. Since 1.8 (2014), you should use java.time.

Add one day at a time until reaching the end date:

int days = Days.daysBetween(startDate, endDate).getDays(); List<LocalDate> dates = new ArrayList<LocalDate>(days);  // Set initial capacity to `days`. for (int i=0; i < days; i++) {     LocalDate d = startDate.withFieldAdded(DurationFieldType.days(), i);     dates.add(d); } 

It wouldn't be too hard to implement your own iterator to do this as well, that would be even nicer.

like image 66
Albert Avatar answered Sep 20 '22 06:09

Albert


java.time Package

If you are using Java 8, there is a much cleaner approach. The new java.time package in Java 8 incorporates the features of the Joda-Time API.

Your requirement can be solved using the below code:

String s = "2014-05-01"; String e = "2014-05-10"; LocalDate start = LocalDate.parse(s); LocalDate end = LocalDate.parse(e); List<LocalDate> totalDates = new ArrayList<>(); while (!start.isAfter(end)) {     totalDates.add(start);     start = start.plusDays(1); } 
like image 20
Yadu Krishnan Avatar answered Sep 20 '22 06:09

Yadu Krishnan