我有一个应用程序,用户可以在其中创建问题,其他人可以 用它查看日期时间(创建问题时)。现在我明白了 服务器日期时间并将其保存在数据库中,但问题是应用程序被使用 生活在时差 6-7 小时的国家/地区的人。 好吧,一个小例子是我住在某个国家,我在晚上 7:00 提出问题,但美国的时间是上午 11 点(只是一个猜测)。所以用户立即检索问题,但对他来说提问时间应该是上午 11 点而不是晚上 7 点。那么我如何保存日期时间以便所有时区都相同。我有点困惑 所以我需要一点帮助。我知道它与 UTC 日期时间有关,但可以 有人详细说明了这一点 :) 。谢谢你
最佳答案
将当前时间与 epoch 之间的差异(以毫秒为单位)存储到您的数据库中UTC 时间 1970 年 1 月 1 日午夜。您可以通过调用 System.currentTimeMillis()
获得。
一旦你有了它,你可以在任何 Time Zone 中提供时间你想要的,这是一个简单的代码 fragment ,它显示了 all the time zones 中的时间在我的机器上可用。
此代码使用 java.time框架内置于 Java 8 及更高版本中。许多此功能也已被 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
,你还必须以 伪标准 格式 GMT+/-mm:ss 将时区 ID 存储到你的数据库中.
为此,首先您需要获取与 UTC 时间相比的增量(在下面的代码 fragment 中,tz
是我当前的时区):
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()));
关于java - 在java中保存所有时区的日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36665799/