我把日期比作字符串很麻烦。我需要遍历一个集合,并将每个对象的日期值与作为参数传递的2个日期进行比较。日期都存储为字符串,我需要保持这种方式。
众所周知,日期将全部格式化YYYY-MM-DD
。以下是我的意思的一个简单示例。谢谢大家!
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;
}
由于您的日期是YYYY-MM-DD
格式,因此可以使用词典比较来确定两个日期之间的顺序。因此,您可以使用String.compareTo()
方法来比较字符串:
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)
}
如果保证dateOne < dateTwo
,那么你可以只使用(c1 >= 0 && c2 <= 0)
。要排除日期范围,请使用严格不等式(>
和<
)。
由于您的日期是yyyy-MM-dd
格式,因此String的compareTo
应返回一致的结果:
if(objectDate.compareTo(dateOne) >= 0 && objectDate.compareTo(dateTwo) <= 0)
这粗略地检查(概念上):objectDate >= dateOne && objectdate <= dateTwo
那就是必须使用字符串方法。一种更好的方法,思想是将字符串转换为日期对象并执行基于日期的比较。
以下是您需要遵循的程序:
java.time.LocalDate
java.time.LocalDate
注意:您需要接受ArrayList<String>
才能将字符串解析为LocalDate,而不是ArrayList<Object>
Refer to the documentation实施比较逻辑。
如果dateOne在dateTwo之前,您可以使用以下比较,如果您希望在其间有日期。
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);
}