MySQL - how to store time with correct timezone? (from Java)

后端 未结 3 455
清歌不尽
清歌不尽 2020-12-11 10:50

I\'m using MySQL 5.0. I need to store date-time information in one column. I mean to use DATETIME or TIMESTAMP column type. But I have problem with

3条回答
  •  孤城傲影
    2020-12-11 11:39

    You could convert the date to UTC before storing in the database, then convert back to your own time zone when reading from the database.

    long t = 1351382400000; // the timestamp in UTC
    String insert = "INSERT INTO my_table (timestamp) VALUES (?)";
    PreparedStatement stmt = db.prepareStatement(insert);
    java.sql.Timestamp date = new Timestamp(t);
    stmt.setTimestamp(1, date);
    stmt.executeUpdate();
    
    .....
    
    TimeZone timezone = TimeZone.getTimeZone("MyTimeZoneId");
    Calendar cal = java.util.Calendar.getInstance(timezone);
    String select = "SELECT timestamp FROM my_table";
    // some code omitted....
    ResultSet rs = stmt.executeQuery();
    while (rs.next()) {
       java.sql.Timestamp ts = rs.getTimestamp(1);
       cal.setTimeInMillis(ts.getTime());
       System.out.println("date in db: " + cal.getTime());
    }
    

提交回复
热议问题