如何在Java中从日期数组中获取最大日期(以YYYYMM格式)?

4

我想从一个以yyyyMM格式表示的日期数组中找出最大的日期。例如,假设我的日期列表如下:

["202210", "202211", "202212", "202301"]

那么正确的值应该是202301

我尝试使用SimpleDateFormat类解析日期并找到最大日期,像这样:

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

如何将 Sun Jan 01 00:00:00 GMT 2023 转换为 202301


2
如果它们是字符串,你可以直接获取最大的一个:Collections.max(dates) - Bruno Marotta
4
请不要使用 SimpleDateFormat - MC Emperor
System.out.println(Collections.max(temp)) 会使用 java.util.DatetoString() 方法,该方法不会使用您所需的格式。 - Mark Rotteveel
5个回答

3
假设您想以与列表相同的原始格式显示最大日期,那么您不需要将其转换为真正的日期,假设日期字符串始终按照 yyyyMM 的格式。在这种情况下,字符串将作为日期正确排序,我们可以直接使用 Collections#max
List<String> dates=Arrays.asList("202210","202211","202212","202301"); 
System.out.println(Collections.max(dates));  // 202301

2
你当然可以对字符串进行排序并获取最后一个值,但如果你想使用可比较的表示一年中某个月份的对象,可以使用 java.time.YearMonth。例如:
public static void main(String[] args) {
    // example values
    String[] monthsWithYears = { "202210","202211","202212","202301" };
    // formatter capable of the String format
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuuMM");
    // map to list of YearMonth and find the maximum
    YearMonth maxYearMonth = Arrays.stream(monthsWithYears)
                                   .map(s -> YearMonth.parse(s, dtf))
                                   .max(YearMonth::compareTo)
                                   .get();
    // print it(s toString() method implicitly)
    System.out.println("Max year month is " + maxYearMonth);
}

输出:

Max year month is 2023-01

2
我建议使用现代日期时间API,如此答案所建议。@deHaaar - 将其简化为 YearMonth maxYearMonth = Arrays.stream(monthsWithYears) .map(s -> YearMonth.parse(s, dtf)) .max(YearMonth::compareTo) .get(); 即您无需先收集它,然后再找到最大值。另外,添加一步。String strMaxYm = dtf.format(maxYearMonth);。这一步很重要,以便OP可以以所需的输入形式获得所需的值。 - Arvind Kumar Avinash
1
完全正确,我的例子可以简化!谢谢,@ArvindKumarAvinash - deHaar
1
比其他建议更美观。原帖作者应该像这里展示的那样使用正确的类型。更好的做法是在列表中保留YearMonth对象而不是字符串。想要以所需格式获得输出,请使用maxYearMonth.format(dtf) - Ole V.V.

2

由于数组的类型为String,因此您可以按照时间顺序找到最大的字符串并使用它。您目前用于查找最大值的逻辑仍将起作用,或者您可以使用一些Collection来为您完成这项工作。

它将为您提供正确的结果,因为您的格式是yyyyMM,这意味着后面的年份始终大于较小年份的字符串值。

例如,"202210"始终小于"202211"或"202301"

将它们视为字符串也将节省计算时间以将它们解析成Date对象。


0

只需将最后一行System.out.println(Collections.max(temp));替换为System.out.println(sdf.format(Collections.max(temp)));


0

使用简单的for循环和字符串比较来确定最大值的另一种解决方案:

List<String> dates=Arrays.asList("202210","202211","202212","202301");
String max = "000000";
for (int i = 0; i < dates.size(); i++) {
    if (dates.get(i).compareTo(max) > 0) {
        max = dates.get(i);
    }
}

System.out.println("Max date is: " + max); //Max date is: 202301

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接