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

问题描述 投票:1回答:4

我把日期比作字符串很麻烦。我需要遍历一个集合,并将每个对象的日期值与作为参数传递的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;
}
java string string-comparison
4个回答
2
投票

由于您的日期是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)。要排除日期范围,请使用严格不等式(><)。


0
投票

由于您的日期是yyyy-MM-dd格式,因此String的compareTo应返回一致的结果:

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

这粗略地检查(概念上):objectDate >= dateOne && objectdate <= dateTwo

那就是必须使用字符串方法。一种更好的方法,思想是将字符串转换为日期对象并执行基于日期的比较。


0
投票

以下是您需要遵循的程序:

  1. 将字符串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


0
投票

如果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);
    }
© www.soinside.com 2019 - 2024. All rights reserved.