【问题标题】:Date Issue From MySQL To Java (TimeZone Addition)从 MySQL 到 Java 的日期问题(时区添加)
【发布时间】:2025-02-21 13:05:01
【问题描述】:

我有一个名为 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 到美国东部标准时间有 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。

【问题讨论】:

  • 你知道为什么当前时区是 EST 而不是 UTC 吗?

标签: java mysql date time


【解决方案1】:

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

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

Date begin = resultSet.getDate("startDate", new GregorianCalendar(TimeZone.getTimeZone("UTC")));

【讨论】:

    【解决方案2】:

    尝试使用:

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

    resultSet.getDate() 返回 java.sql.Date 而不是 java.util.Date

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 我很肯定 JodaTime 会表现出相同的行为。是 MySQL 驱动程序在不应该做的时候试图做一些聪明的事情。因为自 1970 年以来它给我的毫秒数不是自 UTC 以来,而是 EST(+4 小时 -> UTC 凌晨 4 点)。看我的回答。
      • 啊,这很奇怪。我不得不承认我没有使用过TIMESTAMP 列格式。但是,嘿,如果没有盲目的“使用 joda!”,什么日期/时间问题才是完整的。回答? ;)
      【解决方案4】:

      在使用 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)); ...

      【讨论】: