GWT - 显示的时间比数据库中存储的时间晚 1 小时

GWT - Time displayed is 1 hour later than the time stored in the DB

当我在客户端显示时间时,它比存储在数据库中的时间晚一小时(我只将时间存储在 MySQL 作为时间类型)。我喜欢这个解决方案:

            Calendar myCalendar = new GregorianCalendar();
            int gmtOffset = myCalendar.get(Calendar.ZONE_OFFSET);
            int tzOffsetMin = (myCalendar.get(Calendar.ZONE_OFFSET) + myCalendar.get(Calendar.DST_OFFSET))/(1000*60);
            Window.alert("gmtOffset = " + gmtOffset + " tzOffsetMin = " + tzOffsetMin);

但是,当我编译它时出现错误:

[ERROR] Errors in 'file:/C:/Users/Glyndwr/workspace/AwardTracker_N/src/org/AwardTracker/client/HikeDetailsView.java'
      [ERROR] Line 525: No source code is available for type java.util.Calendar; did you forget to inherit a required module?
      [ERROR] Line 525: No source code is available for type java.util.GregorianCalendar; did you forget to inherit a required module?

我发现这是 GWT 的一个已知问题。

那么我如何在 GWT 中找到偏移量以便允许它?如果我简单地减去一个小时,那么当我们从夏令时改为正常时间时,这将是不正确的。

GWT 编译器不支持 java.util.Calendar class,这就是您遇到上述错误的原因。要处理此类日期、时间和时区问题,我建议执行以下步骤

  1. 我建议使用 TIMESTAMP 或将日期对象的时间(毫秒)存储在数据库中。

  2. 从数据库中获取这个值,通过rpc调用传递日期(或毫秒时间)值。

  3. 最后一步是使用 DateTimeFormat 格式化方法显示 Date 对象的时间部分,默认情况下它会考虑 client/browsers 时区并相应地显示值。

浏览器中的客户端 TZ 设置可能会影响它,以及服务器 JVM 的 TZ。如果您希望日期显示在与数据库中完全相同的 TZ 中,请将其存储为字符串,实际上以任何模式,假设 'dd/MM/yyyy hh:mm:ss' 就可以。 然后在客户端使用 DateTimeFormat 反序列化它。

这就是我们在遇到日期的 2 种不同转换(JVM 和客户端浏览器)时所做的事情。希望对你有帮助。

您可以从 TimeZone class.

获取偏移量信息
TimeZone.createTimeZone(String tzJSON)

Fromt GWT 文档:

Applications can get such a string from the TimeZoneConstants class, or it can request the string from the server. Either way, the application obtains the original string from the data provided in the TimeZoneConstant.properties file, which was carefully prepared from CLDR and Olson time zone database.

您通常不希望客户端上有所有这些字符串。我使用 RPC 调用仅检索我需要的字符串。

请注意,不同日期的时区偏移量可能不同。