[英]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;
}
由於您的日期采用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)
。 要排除日期范圍,請使用嚴格的不等式( >
和<
)。
這是您需要遵循的步驟:
java.time.LocalDate
遍歷ArrayList並將索引的字符串轉換為java.time.LocalDate
注意:您需要接受ArrayList<String>
才能將字符串解析為LocalDate,而不是ArrayList<Object>
請參考文檔以實現比較邏輯。
您可以參考此鏈接以獲取其他幫助 。
由於您的日期采用yyyy-MM-dd
格式,因此String的compareTo
應該返回一致的結果:
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.