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

如何将Java Date类型转换为MySQL可识别的yyyy-MM-dd HH:mm:ss格式字符串

Java中Date对象转换为yyyy-MM-dd HH:mm:ss格式字符串的方法

方案一:使用Java 8+ DateTime API(推荐)

Java 8引入的java.time包是线程安全、设计更合理的日期时间处理方案,完全替代老旧的Date/Calendar API。

步骤说明:

  1. 将Date对象转换为Instant(时间戳对象),再通过指定时区转为LocalDateTime
  2. 使用DateTimeFormatter生成目标格式的字符串

代码示例:

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class DateFormatter {
    public static void main(String[] args) {
        // 替换为你通过calendar.getTime()获取的Date对象
        Date date = new Date();
        
        // 指定时区(例如上海时区),避免时区偏移导致的时间误差
        LocalDateTime localDateTime = date.toInstant()
                .atZone(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();
        
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedStr = localDateTime.format(formatter);
        
        System.out.println(formattedStr);
    }
}

方案二:使用旧版SimpleDateFormat(仅兼容旧代码)

SimpleDateFormat是非线程安全的,多线程环境下易引发异常,仅建议用于维护老旧项目。

代码示例:

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

public class OldDateFormatter {
    public static void main(String[] args) {
        // 替换为你的Date对象
        Date date = new Date();
        
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 强制指定时区,避免默认时区差异问题
        sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        
        String formattedStr = sdf.format(date);
        System.out.println(formattedStr);
    }
}

关键提示

  • Date对象本身无格式:你提到的“格式为yyyy-MM-dd的Date对象”是误解——Date本质是一个UTC时间戳,格式只是字符串展示时的表现形式,对象本身不存储格式信息。
  • 插入MySQL的更优方式:如果MySQL字段类型为DATETIME或TIMESTAMP,建议直接通过JDBC的PreparedStatement设置参数,无需转字符串,避免格式与时区问题:
    String sql = "INSERT INTO your_table (datetime_col) VALUES (?)";
    PreparedStatement pstmt = connection.prepareStatement(sql);
    pstmt.setTimestamp(1, new Timestamp(date.getTime()));
    pstmt.executeUpdate();
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 02:24:56