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

如何将SQL的smalldatetime类型数据转为Java的dd.mm.yyyy格式日期

解决方法

方式一:使用Java 8+ 推荐的DateTime API(线程安全)

Java 8及以后版本建议用java.time包下的API,相比旧的Date/SimpleDateFormat更安全、易用。

修改你的代码,将Timestamp转换为LocalDateTime后,用DateTimeFormatter格式化:

for (int i = 0; i < liste.size(); i++) {
    if (liste.get(i).DURUM) {
        String sqlSmallDateTimeString = "2017-10-12 00:00:00";
        Timestamp sqlSmallDateTimeValue = Timestamp.valueOf(sqlSmallDateTimeString);
        
        // 转换为LocalDateTime
        LocalDateTime localDateTime = sqlSmallDateTimeValue.toLocalDateTime();
        // 定义格式化器:注意MM是月份(大写,小写mm代表分钟)
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
        // 生成目标格式的日期字符串
        String formattedDate = localDateTime.format(formatter);
        
        liste.get(i).BASTARIH = formattedDate;
    }
}

方式二:使用旧版SimpleDateFormat(注意线程安全问题)

如果项目基于Java 7及以下,只能用SimpleDateFormat,但要注意这个类不是线程安全的,不要在多线程环境下共享同一个实例:

for (int i = 0; i < liste.size(); i++) {
    if (liste.get(i).DURUM) {
        String sqlSmallDateTimeString = "2017-10-12 00:00:00";
        Timestamp sqlSmallDateTimeValue = Timestamp.valueOf(sqlSmallDateTimeString);
        Date dateValue = new Date(sqlSmallDateTimeValue.getTime());
        
        // 每次循环创建实例,或确保仅在单线程环境使用
        SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
        String formattedDate = sdf.format(dateValue);
        
        liste.get(i).BASTARIH = formattedDate;
    }
}

实际数据库获取的注意点

如果是直接从SQL数据库查询smalldatetime类型数据,不需要手动转换字符串,直接用ResultSet.getTimestamp()获取对象即可:

// 假设rs是你的ResultSet实例
Timestamp dbTimestamp = rs.getTimestamp("你的字段名");
// 后续格式化步骤和上面一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 15:42:16