You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中如何获取yyyyMM格式日期数组的最大日期并转回原格式

解决方法

方法一:用SimpleDateFormat格式化结果

你已经成功找到最大的Date对象,只需用同一个SimpleDateFormat实例调用format()方法,就能把Date对象转回yyyyMM格式的字符串:

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();
}
Date maxDate = Collections.max(temp);
// 格式化输出为yyyyMM格式
System.out.println(sdf.format(maxDate)); // 输出202301

方法二:直接比较字符串(更高效)

yyyyMM格式的字符串本身是按「年+月」的数字顺序排列的,字符串的字典序和日期的先后顺序完全一致,因此不需要解析成Date对象,直接比较字符串就能找到最大值:

List<String> dates = Arrays.asList("202210", "202211" ,"202212", "202301");
String maxDateStr = Collections.max(dates);
System.out.println(maxDateStr); // 直接输出202301

这种方法省去了日期解析的开销,代码更简洁,还能避免ParseException的异常处理。

补充:Java 8+推荐使用新日期API

SimpleDateFormat存在线程不安全问题,Java 8及以上版本推荐使用DateTimeFormatter和YearMonth类,更安全且功能更完善:

import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class Main {
    public static void main(String[] args) {
        List<String> dates = Arrays.asList("202210", "202211" ,"202212", "202301");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
        
        Optional<YearMonth> maxYearMonth = dates.stream()
                .map(str -> YearMonth.parse(str, formatter))
                .max(YearMonth::compareTo);
        
        if (maxYearMonth.isPresent()) {
            System.out.println(maxYearMonth.get().format(formatter)); // 输出202301
        }
    }
}

内容的提问来源于stack exchange,提问作者user20980801

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 14:16:24