I want to find out the largest date from an array of dates in yyyyMM format. For example, suppose my arraylist of dates are:
["202210", "202211", "202212", "202301"]
then the correct value should be 202301
I tried using the SimpleDateFormat class and then parse the dates and then find the max date, like this:
List<String> dates = Arrays.asList("202210", "202211" ,"202212", "202301");
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM", Locale.getDefault());
List<Date> temp = new ArrayList<>();
try {
for (String date: dates) {
temp.add(sdf.parse(date));
}
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(Collections.max(temp)); //shows Sun Jan 01 00:00:00 GMT 2023
How do I convert the Sun Jan 01 00:00:00 GMT 2023 to 202301?
Assuming you want to display the max date in the same original format as the list, you need not convert to a bona fide date, assuming the date strings are always in the format yyyyMM. In this case, the strings will sort properly as dates, and we can simply use Collections#max directly:
List<String> dates=Arrays.asList("202210","202211","202212","202301");
System.out.println(Collections.max(dates)); // 202301
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With