简体   繁体   中英

Java & MySQL timezone issue

I am trying to convert a string date value in java to date and trying to store it in a mysql table.

Below the code snippet:

DateFormat dfm = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
String string = "07/24/2013 17:57:52 UTC";
Date a = dfm.parse(string);
System.out.println(a);

My problem is that the above code always returns the following console output: Wed Jul 24 17:57:52 PDT 2013

I don't know why the time zone is getting changed, more over when I am trying to put this into the database then it is storing it in '2013-07-24 17:57:52' format. I am not sure why the above code is returning me timezone in PDT?

Can you guys please explain me that? My intent is to store a UTC date which will come as an input and store it into the MySQL timestamp field.

Thanks in Advance.

Right, if you can fix the string to not include the time zone, it's simpler. Firstly, you need to understand that a Date object doesn't contain a time zone at all - it's just a point in time.

Next, as we're trying to parse a date/time specified in UTC, you should set that in the SimpleDateFormat :

DateFormat dfm = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
dfm.setTimeZone(TimeZone.getTimeZone("UTC"));

Now at that point I'd hope that JPA would do the right thing. You'd at least be passing the right value to the Timestamp constructor.

However, this part of the MySQL documentation makes me nervous:

MySQL converts TIMESTAMP values from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval. (This does not occur for other types such as DATETIME.)

It sounds like you may want to use a DATETIME field instead, to stop this time zone conversion. Setting the time zone of the connection to UTC would help when storing it, but you'd still need to worry about what would happen when fetching. (Databases are pretty messed up when it comes to date/time types, IMO. This is just another example of that...) On the other hand, if you're fetching the data back with Java as well, I'd hope that it would just work transparently. It's probably worth at least trying that...

You are missing the timezone part in your format string. "UTC" is therefore ignored. Try this:

DateFormat dfm = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z"); // added "z"
// then the rest of your code as-is
String string = "07/24/2013 17:57:52 UTC";
Date a = dfm.parse(string);
System.out.println(a); // prints "Wed Jul 24 19:57:52 CEST 2013" for me

Further to @JonSkeet 's word of warning, MySQL "current time zone" can be checked or changed through the time_zone session variable.

Either make sure your session is set to UTC ( SET time_zone = '+0:00' ), or use a DATETIME type instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM