将当前时间与 UTC 1970 年 1 月 1 日午夜的epoch 之间的差值(以毫秒为单位)存储到您的数据库中。您可以拨打System.currentTimeMillis()获取。
一旦你有了它,你可以在任何你想要的Time Zone中提供时间,这里有一个简单的代码sn-p,它显示了我机器上可用的all the time zones中的时间。
此代码使用 Java 8 及更高版本中内置的 java.time 框架。 back-ported to Java 6 & 7 和 to Android 也提供了大部分此类功能。
long time = System.currentTimeMillis();
Instant instant = Instant.ofEpochMilli(time);
ZoneId.getAvailableZoneIds().stream().forEach(id -> {
ZoneId zId = ZoneId.of(id);
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zId);
System.out.printf(
"The current time in %s is %s%n",
zId, localDateTime.format(DateTimeFormatter.ISO_DATE_TIME)
);
}
);
这是旧版本 Java 的等效项:
long time = System.currentTimeMillis();
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(time);
for (String id : TimeZone.getAvailableIDs()) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
formatter.setTimeZone(TimeZone.getTimeZone(id));
System.out.printf(
"The current time in %s is %s%n", id, formatter.format(cal.getTime())
);
}
响应更新:
由于您想保留原始 TimeZone,您还必须将时区 ID 以 伪标准格式 GMT+/-mm:ss 存储到您的数据库中。
为此,首先您需要获取与 UTC 时间相比的增量(在 tz 下面的代码 sn-p 中是我当前的时区):
int offsetFromUTC = tz.getOffset(time);
然后您可以将这个增量(以毫秒为单位)转换为预期的时区 ID,可以这样完成:
String timeZoneId = String.format(
"GMT%+02d:%02d", offsetFromUTC / (60 * 60 * 1000), offsetFromUTC / (60 * 1000) % 60
);
timeZoneId 的值是您必须存储到数据库中的第二个值。使用这两个值,您可以以任何预期的格式显示时间,例如:
Calendar cal = Calendar.getInstance();
// Here I use the time retrieved from the DB
cal.setTimeInMillis(time);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
// Here I use the time zone id retrieved from the DB
TimeZone tz = TimeZone.getTimeZone(timeZoneId);
formatter.setTimeZone(tz);
System.out.printf("The current time in %s is %s%n", id, formatter.format(cal.getTime()));