将日期作为 Java 中的字符串进行比较

Comparing dates as strings in Java

我无法将日期作为字符串进行比较。我需要遍历一个集合并将每个对象的日期值与作为参数传递的 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;
}

这是您需要遵循的程序:

  1. 将String dateOne、String dateTwo都转换成 java.time.LocalDate
  2. 遍历您的 ArrayList 并将索引字符串转换为 java.time.LocalDate

    注意:您需要接受ArrayList<String>才能将字符串解析为LocalDate,而不是ArrayList<Object>

  3. 进行比较

Refer to the documentation 实现比较逻辑。

您可以参考this link for additional help

由于您的日期采用 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 格式,因此字符串的 compareTo 应该 return 一致的结果:

if(objectDate.compareTo(dateOne) >= 0 && objectDate.compareTo(dateTwo) <= 0)

这大致检查(概念上):objectDate >= dateOne && objectdate <= dateTwo

如果必须使用字符串的方法,那就是这样。不过,更好的方法是将字符串转换为日期对象并执行基于日期的比较。

如果 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);
    }