在 Java 中的时区之间转换

Convert between timezone in Java

我正在以 MM/dd/yyyy hh:mm a z 格式从数据库中读取时间,现在我想以用户本地时区显示这个时间。所以我的问题是:

  1. 应该在哪里完成客户端或服务器端?
  2. 是否有为此目的构建的库?

更新 所以我决定在服务器上进行转换,因此我有如下方法定义,其中包含来自服务器的参数日期和客户端时间的时区偏移量。

public String convertToLocalDateTime(Date dateFromDB, Integer offSetMins) {
  //1. dbDateInUTC = Convert dateFromDB to UTC
  //2. return offSetMins + dbDateInUTC;
}

我不确定如何执行第 (1) 步。有什么建议吗?

为了确保用户获得它的时区,您可以在客户端执行此操作,为此您可以使用像 Moment.js or date.js.

这样的库

只获取服务器的日期,将其转换成long:

Date d = // date from server
long milliseconds = d.getTime(); 

发送给客户端并获取偏移量:

The time-zone offset is the difference, in minutes, between UTC and local time. Note that this means that the offset is positive if the local timezone is behind UTC and negative if it is ahead. For example, if your time zone is UTC+10 (Australian Eastern Standard Time), -600 will be returned. Daylight saving time prevents this value from being a constant even for a given locale.

var offset = new Date().getTimezoneOffset();

然后你只需要得到更正后的日期 1 分钟 = 60.000 毫秒 :

var dateInMilliseconds = dateFromServer - (offset * 60000);

此外,如果按照 @jon 的建议,您想告诉服务器客户端的时区,获取 offset 并将其发送到 java 以转换日期:

long offsetMillis = offset * 60000;
Date d = new Date(offsetMillis);

在我的实践中,为了避免复杂和混乱,最好是:

  1. 对于应用程序中的操作和持久日期,请使用 UTC 时区。
  2. 使用本地时区向最终用户显示 date/time。

因此,服务器端全部 dates/times 使用 UTC,客户端使用本地 TZ。