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

Java:如何用SimpleDateFormat处理两种日期输入并统一输出格式?

解决日期格式兼容与统一输出问题

你的问题核心在于解析格式和输入字符串不匹配:input1里的月份是单数字(1),但你定义的format用了MM(要求必须是两位月份,比如01),直接用这个SimpleDateFormat解析input1会抛出ParseException。要同时兼容两种输入并输出统一格式,你需要分两步:先做兼容解析,再按目标格式输出。

方案1:使用旧版SimpleDateFormat(Java 7及以下)

先创建一个支持1位/2位日、月的解析格式,再用目标格式输出统一结果:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateHandler {
    public static void main(String[] args) throws ParseException {
        String input1 = "12-1-2012 T 10:23:34";
        String input2 = "20-10-2012 T 10:34:22";
        
        // 解析器:d/M 支持1位或2位数字,兼容两种输入格式
        SimpleDateFormat dateParser = new SimpleDateFormat("d-M-yyyy T HH:mm:ss");
        // 格式化器:输出你需要的目标格式
        SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy T HH:mm:ss");
        
        // 处理input1
        Date date1 = dateParser.parse(input1);
        String output1 = dateFormatter.format(date1);
        System.out.println(output1); // 输出:12-01-2012 T 10:23:34
        
        // 处理input2
        Date date2 = dateParser.parse(input2);
        String output2 = dateFormatter.format(date2);
        System.out.println(output2); // 输出:20-10-2012 T 10:34:22
    }
}

关键细节:

  • d和M是灵活的模式字符:它们可以匹配1位或2位数字(比如1或01都能匹配M),而dd/MM则强制要求两位数字,缺少前导零就会解析失败。
  • 注意:SimpleDateFormat是线程不安全的,如果在多线程环境中使用,建议每次创建新实例,或者用ThreadLocal来管理实例。

方案2:使用Java 8+的新日期API(推荐)

Java 8引入的java.time包解决了旧API的诸多问题(比如线程不安全),用DateTimeFormatter实现会更可靠:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class ModernDateHandler {
    public static void main(String[] args) {
        String input1 = "12-1-2012 T 10:23:34";
        String input2 = "20-10-2012 T 10:34:22";
        
        // 构建兼容解析器:支持1位/2位的日和月
        DateTimeFormatter parser = DateTimeFormatter.ofPattern("d-M-yyyy' T 'HH:mm:ss");
        // 目标格式器
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy' T 'HH:mm:ss");
        
        // 处理input1
        LocalDateTime dateTime1 = LocalDateTime.parse(input1, parser);
        String output1 = dateTime1.format(formatter);
        System.out.println(output1); // 输出:12-01-2012 T 10:23:34
        
        // 处理input2
        LocalDateTime dateTime2 = LocalDateTime.parse(input2, parser);
        String output2 = dateTime2.format(formatter);
        System.out.println(output2); // 输出:20-10-2012 T 10:34:22
    }
}

优势:

  • DateTimeFormatter是线程安全的,适合在多线程场景复用。
  • API设计更直观,避免了旧API的空指针、时区处理混乱等潜在问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 16:56:14