Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the maximum date (in YYYYMM format) from an array of dates in java?

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?


1 Answers

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
like image 90
Tim Biegeleisen Avatar answered Nov 03 '25 21:11

Tim Biegeleisen