字符串日期转日期类型解决ArrayList排序异常问题
Got it, let's fix that sorting issue you're having. The problem here is exactly what you suspected—when you compare date strings directly with Comparator.comparing(matches::getDate), Java is doing a lexicographical (dictionary-style) comparison instead of recognizing the actual date order. For example, a string like 01/12/2024 would come after 15/01/2023 in string order, but the latter is actually an earlier date.
Here's how to fix this by converting those string dates and times into proper date-time objects before comparing:
Step-by-Step Solution
First, use Java 8+'s java.time API (far safer and more intuitive than the old SimpleDateFormat) to parse your string values into date-time objects. We'll use DateTimeFormatter to match your dd/MM/yyyy date format, plus a formatter for your time strings.
- Define the formatters (adjust the time pattern if your
getTime()returns a different format likeHH:mm:ss):
import java.time.LocalDate; import java.time.LocalTime; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Comparator; // ... DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy"); DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm"); // Match your actual time string format
- Modify your sort comparator to parse the strings into valid date-time types before comparing. You have two clean options:
Option 1: Combine Date + Time into a Single LocalDateTime
This creates a unified timestamp for each match, making the comparison straightforward:
matchesList.sort(Comparator.comparing(match -> { LocalDate date = LocalDate.parse(match.getDate(), dateFormatter); LocalTime time = LocalTime.parse(match.getTime(), timeFormatter); return LocalDateTime.of(date, time); }));
Option 2: Chain Date Comparison First, Then Time
If you prefer to keep date and time comparisons separate (same end result):
matchesList.sort(Comparator.comparing((Match match) -> LocalDate.parse(match.getDate(), dateFormatter)) .thenComparing(match -> LocalTime.parse(match.getTime(), timeFormatter)));
Key Notes
- Exception Safety: If there's any chance your Firebase data has malformed date/time strings, wrap the parse calls in a
try-catchblock to handleDateTimeParseException, or validate the data before storing it in Firebase to avoid issues entirely. - Legacy Java Support: If you're stuck on Java 7 or earlier, you'll need to use
SimpleDateFormatandDateinstead, but upgrading to Java 8+ is highly recommended for better date-time handling.
With this approach, the comparator will respect the actual chronological order of your dates and times, so your sort will work exactly as you expect.
内容的提问来源于stack exchange,提问作者Carl Bruiners

