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

后端 未结 5 1148
悲&欢浪女
悲&欢浪女 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:16

    Well, if we're talking about using PreparedStatements, there's a form of setDate where you can pass in a Calendar set to a particular time zone.

    For instance, if you have a PreparedStatement named stmt, a Date named date, and assuming the date is the second parameter:

    stmt.setDate(2, date, Calendar.getInstance(TimeZone.getTimeZone("GMT")));
    

    The best part is, even if GMT is an invalid time zone name, it still returns the GMT time zone because of the default behavior of getTimeZone.

提交回复
热议问题