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

Android应用获取当前日期存入MySQL:阿拉伯语环境日期异常问题

解决Android多语言环境下日期插入MySQL异常问题

问题根源在于SimpleDateFormat默认会采用系统当前的Locale,当手机切换为阿拉伯语Locale时,格式化生成的时间字符串会包含阿拉伯数字格式,而MySQL无法识别这类非标准格式的时间,最终导致插入后显示为0000-00-00。

修复方案1:指定Locale为英语

创建SimpleDateFormat时明确指定英语Locale,确保无论系统语言如何,都生成MySQL能识别的标准格式字符串:

public String getTime() {
    Date dt = new Date();
    // 指定Locale为ENGLISH,避免系统语言影响格式输出
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH);
    String currentTime = sdf.format(dt);
    return currentTime;
}

如果需要处理日期(如yyyy-MM-dd),同样要在创建SimpleDateFormat时指定Locale.ENGLISH。

修复方案2:使用PreparedStatement直接传入时间对象

更稳妥的方式是跳过字符串格式化环节,直接通过PreparedStatement的setTimestamp方法传入时间对象,由数据库驱动负责格式转换,彻底规避Locale带来的问题:

// 示例:插入时间到数据库
try (Connection conn = getDatabaseConnection()) {
    String sql = "INSERT INTO your_table (time_column) VALUES (?)";
    PreparedStatement pstmt = conn.prepareStatement(sql);
    // 直接传入Timestamp对象,无需手动格式化
    pstmt.setTimestamp(1, new Timestamp(new Date().getTime()));
    pstmt.executeUpdate();
} catch (SQLException e) {
    e.printStackTrace();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 14:31:06