Reputation: 35
I am having troubles comparing dates as strings. I am required to iterate through a collection and compare the date value of each object against 2 dates passed as parameters. The dates are all stored as strings and am required to keep them that way.
It is known that the dates will all be formatted YYYY-MM-DD
. Below is a quick example of what I mean. Thanks all!
public ArrayList<Object> compareDates(String dateOne, String dateTwo) {
for(Object object : objectCollection) {
String objectDate = object.getDate();
if(objectDate.equals(dateOne) || objectDate.equals(dateTwo)) { // Unsure of how to determine if the objects date is inbetween the two given dates
//add object to collection
}
}
return collection;
}
Upvotes: 2
Views: 5053
Reputation: 406
Since your dates are in the YYYY-MM-DD
format, a lexicographic comparison can be used to determine the ordering between two dates. Thus, you can just use the String.compareTo()
method to compare the strings:
int c1 = objectDate.compareTo(dateOne);
int c2 = objectDate.compareTo(dateTwo);
if ((c1 >= 0 && c2 <= 0) || (c1 <= 0 && c2 >= 0)) {
// objectDate between dateOne and dateTwo (inclusive)
}
If it is guaranteed that dateOne < dateTwo
, then you can just use (c1 >= 0 && c2 <= 0)
. To exclude the date bounds, use strict inequalities (>
and <
).
Upvotes: 3
Reputation: 2219
If dateOne is before dateTwo you can use following comparison if you like have date inbetween.
public ArrayList<Object> compareDates(List<Object> objectCollection, String start, String end) {
ArrayList<Object> dateBetween = new ArrayList<>();
for(Object object : objectCollection) {
LocalDate objectDate = parseDate(object.getDate());
if( !objectDate.isBefore(parseDate(start)) && !objectDate.isAfter(parseDate(end))) {
dateBetween.add(object);
}
}
return dateBetween;
}
private LocalDate parseDate(String date) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY-MM-DD");
return LocalDate.parse(date, formatter);
}
Upvotes: 0
Reputation: 4460
Here is the procedure you need to follow:
java.time.LocalDate
Iterate over your ArrayList and convert the indexed string into java.time.LocalDate
Note: You need to accept ArrayList<String>
in order to parse the string to LocalDate, not ArrayList<Object>
Refer to the documentation to implement the comparison logic.
You may refer to this link for additional help.
Upvotes: 0
Reputation: 45319
As your dates are in the yyyy-MM-dd
format, then String's compareTo
should return consistent results:
if(objectDate.compareTo(dateOne) >= 0 && objectDate.compareTo(dateTwo) <= 0)
This roughly checks (conceptually): objectDate >= dateOne && objectdate <= dateTwo
That's just if one must use string's methods. A better approache, though, would be to convert the strings to date objects and perform a date-based comparisons.
Upvotes: 0