我有一个名为 startDate
的字段,类型为 TIMESTAMP
我从 MySQL InnoDB 数据库中获取:
SELECT startDate FROM jn.all WHERE id IN(115)
=> 2012-07-28 00:00:00
在 Java 中我这样做:
java.util.Date d = resultSet.getDate("startDate");
SimpleDateFormat tsmpFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
tsmpFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(tsmpFormatter.format(d));
我得到:
=>2012-07-28 04:00:00
从 UTC 到 EST 有 4 个小时。数据库时间是 UTC。
SELECT now();
=> 2013-07-29 21:46:26
虽然我现在的美国东部时间是 17:46:26
即使我在所有地方都使用 UTC,为什么我还是会得到这 4 个小时的时差?谢谢!
编辑:
我可能已经发现了问题。
http://dev.mysql.com/doc/refman/5.1/en/datetime.html
MySQL 将 TIMESTAMP 值从当前时区转换为 UTC 进行存储,然后从 UTC 转换回当前时区进行检索。 (对于 DATETIME 等其他类型不会发生这种情况。)
但是这个当前时区
是什么?服务器应采用 UTC。
最佳答案
对不起大家,找到我自己的答案。这个解决方案在我看来很荒谬,但你能做什么。
从结果集中获取数据时,我必须传递一个日历。
Date begin = resultSet.getDate("startDate", new GregorianCalendar(TimeZone.getTimeZone("UTC")));
关于java - 从 MySQL 到 Java 的日期问题(时区添加),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17934786/