How to store a java.util.Date into a MySQL timestamp field in the UTC/GMT timezone?

后端 未结 5 1145
悲&欢浪女
悲&欢浪女 2020-12-24 03:35

I used a new Date() object to fill a field in a MySQL DB, but the actual value stored in that field is in my local timezone.

How can I configure MySQL to store it in

5条回答
  •  情话喂你
    2020-12-24 04:00

    I had the same problem, and it took me nearly a day to track down. I'm storing DateTime columns in MySQL. The RDS instance, running in Amazon's Cloud, is correctly set to have a UTC timestamp by default.

    The Buggy Code is:

        String startTime = "2013-02-01T04:00:00.000Z";
        DateTime dt = ISODateTimeFormat.dateTimeParser().parseDateTime(startTime);            
    
        PreparedStatement stmt = connection.prepareStatement(insertStatementTemplate);
    
        Timestamp ts = new Timestamp(dt.getMillis());
        stmt.setTimestamp(1, ts, Calendar.getInstance(TimeZone.getTimeZone("UTC"))); 
    

    In the code above, the ".setTimestamp" call would NOT take the date as a UTC date!

    After hours of investigating, this turns out to be a known bug in the Java / MySQL Driver. The call to setTimestamp listerally just ignores the Calendar parameter.

    To fix this add the "useLegacyDatetimeCode=false" to your database URI.

    private final static String DatabaseName =
      "jdbc:mysql://foo/?useLegacyDatetimeCode=false";
    

    As soon as i did that, the date stored in the MySQL database was in proper UTC form, rather than in the timezone of my local workstation.

提交回复
热议问题