我有一个应用程序,用户可以在其中创建问题,其他人可以使用它查看日期时间(创建问题时)。现在,我获取服务器日期时间并将其保存在db中,但问题是居住在有6-7小时间隔的国家/地区的人使用了app。很好的一个小例子是,我住在某个国家,我在晚上7:00提出问题,但在美国的时间是上午11点(只是一个猜测)。因此,用户可以立即检索问题,但对他来说,问题时间应该是上午11点而不是晚上7点。所以我该如何保存日期时间,以便所有时区都一样。我有点困惑,所以我需要一点帮助。我知道这与UTC日期时间有关,但是有人可以详细说明一下:)。感谢你
存储到数据库中的差异,以毫秒为单位,当前时间和与时代午夜,1970年1月1日UTC。您可以通过致电获得System.currentTimeMillis()
。
有了它后,就可以在所需的任何时区中提供时间,这是一个简单的代码段,显示了计算机上所有可用时区中的时间。
此代码使用Java 8及更高版本中内置的java.time框架。许多功能也已反向移植到Java 6和7以及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时间相比的增量(下面的代码段tz
是我当前的TimeZone):
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()));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句