1

我有一个名为我从 MySQL InnoDB 数据库获得的startDate类型的字段:TIMESTAMP

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

虽然我目前的 EST 时间是 17:46:26

即使我到处使用 UTC,为什么我会得到这 4 小时的差异?谢谢!

编辑:

我可能发现了这个问题。

http://dev.mysql.com/doc/refman/5.1/en/datetime.html

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.)

但这是什么current time zone?服务器应该是 UTC。

4

4 回答 4

2

对不起大家,找到我自己的答案。这个解决方案在我看来很荒谬,但你能做什么。

从结果集中获取数据时,我必须传递一个日历。

Date begin = resultSet.getDate("startDate", new GregorianCalendar(TimeZone.getTimeZone("UTC")));
于 2013-07-29T22:06:18.433 回答
0

尝试使用:

java.sql.Timestamp ts = resultSet.getTimestamp("mvStartDate");

resultSet.getDate()返回java。sql .Date 而不是 java。实用程序.日期

用java。util .Date 你松散的时间信息。

于 2013-07-29T21:48:02.690 回答
0

我确定您已经在其他地方阅读过此内容,但您可能会考虑查看Joda Time,它知道时区并且可以忽略它们。

这是一种精神上的投资,但在灵活性和力量方面是值得的。

于 2013-07-29T22:04:30.447 回答
0

在使用 java.util.date 之前,您应该了解默认时区。您的代码可能是:

    ...
    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
    ...
    java.util.Date d = resultSet.getDate("mvStartDate");
    SimpleDateFormat tsmpFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    tsmpFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    System.out.println(tsmpFormatter.format(d));
    ...
于 2013-07-29T22:59:22.033 回答