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

如何用Java将PostgreSQL返回的多格式日期统一为指定格式

统一转换PostgreSQL日期格式的Java实现方案

首先来说你遇到的报错问题:你用的new Date(String)构造方法早就被标记为过时了,它对日期字符串的格式要求非常苛刻,"2017-11-27 00:00:00"这种格式不在它能识别的范围内,所以才会抛出IllegalArgumentException。而且这个方法的行为还依赖系统默认的区域设置,很不稳定,绝对不推荐在生产代码里使用。

接下来给你两种可行的解决方案,分别适配Java 8之前和之后的版本:

方案一:使用Java 8之前的SimpleDateFormat

我们需要先定义所有可能从PostgreSQL拿到的日期格式,然后逐个尝试解析,成功后再转成你需要的dd/MM/yyyy格式。代码示例如下:

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

public class DateConverter {
    public static void main(String[] args) {
        // 模拟从数据库拿到的各种日期字符串
        String[] inputDates = {
            "2015-11-26 09:30:10",
            "2015-11-26 09:30:10.080",
            "2015-11-26 09:30:10.000",
            "2017-11-27 00:00:00"
        };
        
        // 定义所有可能的输入格式,覆盖你提到的三种情况
        String[] inputFormats = {
            "yyyy-MM-dd HH:mm:ss",
            "yyyy-MM-dd HH:mm:ss.SSS"
        };
        
        // 目标输出格式
        SimpleDateFormat outputFormat = new SimpleDateFormat("dd/MM/yyyy");
        
        for (String dateStr : inputDates) {
            Date parsedDate = null;
            // 逐个尝试解析,直到找到匹配的格式
            for (String format : inputFormats) {
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat(format);
                    sdf.setLenient(false); // 开启严格解析,避免格式不对却意外解析成功
                    parsedDate = sdf.parse(dateStr);
                    break;
                } catch (ParseException e) {
                    // 这个格式不行,继续试下一个
                    continue;
                }
            }
            
            if (parsedDate != null) {
                String formattedDate = outputFormat.format(parsedDate);
                System.out.println("原日期: " + dateStr + " → 转换后: " + formattedDate);
            } else {
                System.out.println("无法解析日期: " + dateStr);
            }
        }
    }
}

这里有个关键细节:setLenient(false)一定要加上,不然SimpleDateFormat会进行宽松解析,比如把不符合格式的字符串强行转换成日期,导致结果错误。

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

从Java 8开始,引入了全新的日期时间API(java.time包),它不仅线程安全,而且API设计更清晰,处理日期格式也更灵活。代码示例如下:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Arrays;
import java.util.List;

public class ModernDateConverter {
    public static void main(String[] args) {
        List<String> inputDates = Arrays.asList(
            "2015-11-26 09:30:10",
            "2015-11-26 09:30:10.080",
            "2015-11-26 09:30:10.000",
            "2017-11-27 00:00:00"
        );
        
        // 定义所有可能的输入格式
        List<DateTimeFormatter> inputFormatters = Arrays.asList(
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"),
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")
        );
        
        // 目标输出格式
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
        
        for (String dateStr : inputDates) {
            LocalDateTime parsedDateTime = null;
            for (DateTimeFormatter formatter : inputFormatters) {
                try {
                    parsedDateTime = LocalDateTime.parse(dateStr, formatter);
                    break;
                } catch (DateTimeParseException e) {
                    // 格式不匹配,继续尝试下一个
                    continue;
                }
            }
            
            if (parsedDateTime != null) {
                String formattedDate = parsedDateTime.format(outputFormatter);
                System.out.println("原日期: " + dateStr + " → 转换后: " + formattedDate);
            } else {
                System.out.println("无法解析日期: " + dateStr);
            }
        }
    }
}

这个方案的优势很明显:

  • DateTimeFormatter是线程安全的,在多线程环境下不用每次都创建新实例
  • 日期时间类型(比如LocalDateTime)语义更清晰,避免了旧Date类的混乱
  • 错误处理更明确,DateTimeParseException能精准提示解析失败的原因

总结一下:不要再用过时的Date(String)构造方法了,不管用哪种方案,都要明确指定输入格式来解析日期字符串,这样才能稳定处理你从PostgreSQL拿到的各种日期格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:59:15