This question already has an answer here:
I'm trying to get an array of Dates, while my input is a 'from'/'to' structure. So my input is:
String date1 = "2014-01-01";
String date2 = "2014-05-01";
My output should be an Arraylist with all dates between date1 and date2. I've already looked for this, but I could only find questions about the difference between 2 dates:
SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
String inputString1 = "23 01 1997";
String inputString2 = "27 04 1997";
try {
Date date1 = myFormat.parse(inputString1);
Date date2 = myFormat.parse(inputString2);
long diff = date2.getTime() - date1.getTime();
System.out.println ("Days: " + TimeUnit.DAYS.convert(diff,TimeUnit.MILLISECONDS));
} catch (ParseException e) {
e.printStackTrace();
}
Any hints or suggestions? All other questions are for iOS or SQL.
If you don't want to use third party libraries you can use
Calendar
:Check here a working demo.
Take a look at JodaTime: http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTime.html
In case you are using Guava, there is a very elegant solution to this problem.
Guava has two neat classes, such as Range and ContiguousSet, which implement exactly what you need: first one operates on ranges of values, and second one - is able to convert a range to a set of discrete values.
Example of usage of both (together with JodaTime):
Personally, I really prefer this way, as it eliminates some problems with understanding closed/open ranges, and makes code much easier to read and understand, while making no impact on performance. Also, it works with any kinds of dates, any libraries (you can swap YodaTime to Java8 Dates or even Java7- Date-based implementation).
Moreover, it allows you to do some neat operations on ranges like intersections, unions, spanning of ranges, incredibly fast "contains" and so on.
Only downsides are:
Example of LocalDateDomain implementation which operates as a bridge between Guava and JodaTime:
I already know that OP isn't using Java 8 but here's the current solution - Java has been revamped and the new
java.time
API does every conceivable job in that regard:This will output every valid day between the two dates whereas most of the other solutions will also give you invalid ones; heres the thing: temporal calculations need to be done on timezone-independent data - the output on the other hand may very well be timezone and/or chronology -dependent. Thats why there are packages like
java.time.format
- simply calculate your time/date values and format them for your chosen region ... thats how its done correctly.If you need to convert temporal input there are also useful functions in the time-API, i recommend doing a thorough tutorial on the subject, a few good introductions may be this and especially that :
Below is the code to get array of dates between the two string date.
I like JodaTime, but this can also be done without 3rd party libraries by using
java.util.Calendar
. Given aCalendar
object, one can use itsadd
method to increase certain fields of the date while honoring the calendar rules (like adding 1 day to the 31st of January gets you to the 1st of February, not to the 32nd of January).First get the dates into one
Calendar
object each, in the correct chronological order so adding is going in the right direction later:date1
anddate2
are the parsedDate
objects from your question, for simplicity's sake.Next, loop over an "add 1 to day-of-year" instruction until this gets you beyond the stop date:
And lastly print the stop date
pretty()
is just some mini method sending the calendar through a SDF, like the one you used for parsing the Strings in the first place.This solution will print the date range, including the start and stop dates, and might need some tweaking around the edge cases (like
date1==date2
). Can be easily adapted to exclude the start and stop dates. Printing can be swapped for aggregation of course. To get a Date object from the calendar, use thegetTime()
method (returns a snapshot, not a live reference).The documentation for the relevant
(Gregorian)Calendar
can be found here.