【发布时间】:2015-07-26 21:10:28
【问题描述】:
使用 joda,如何将 UTC+/-n 时间格式化为“墙上时间”以显示给用户:
从 (UTC+/-n):
2015-05-15T03:28:49.523-04:00
到(EST)墙:
2015-05-14 23:22:44
更新(1)
请考虑以下代码。我们需要使用时间戳 用于在 UTC 中写入和写入数据库。考虑到这一点:
DateTimeZone.setDefault(DateTimeZone.UTC);
LocalDateTime utcDate = new LocalDateTime();
DateTimeZone utcTZ = DateTimeZone.forTimeZone(TimeZone.getTimeZone("ETC/UTC"));
DateTimeZone localTZ = DateTimeZone.forTimeZone(TimeZone.getTimeZone("America/Montreal"));
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
fmt.withZone(localTZ);
DateTime localDateTime = utcDate.toDateTime(localTZ);
DateTime utcDateTime = localDateTime.toDateTime(utcTZ);
Timestamp u = new Timestamp(utcDateTime.getMillis());
System.out.println("UTC Time: " + u);
LocalDateTime date = new LocalDateTime(u);
DateTime srcDateTime = date.toDateTime(utcTZ);
DateTime dstDateTime = srcDateTime.toDateTime(localTZ);
System.out.println("UTC+/- Time: " + dstDateTime.toString());
DateTime dateTimeInTargetTimezone = dstDateTime.withZone(localTZ);
System.out.println("Wall Time: " + dateTimeInTargetTimezone.toString("yyy-MM-dd HH:mm:ss"));
现在,当在 Timestamp 对象中从数据库中提取 UTC 时间时,我们需要 在“Wall/Funeral Time”中向最终用户显示时间,无论您想如何称呼它,在他们的 TZ 中。
输出
UTC Time: 2015-05-15 20:03:47.561 "Good"
UTC+/- Time: 2015-05-15T20:03:47.561-04:00 "Good"
Wall Time: 2015-05-15 20:03:47 "No! No! No! Danger! We'll be late!"
这名字是什么!我必须做些什么才能让dstDateTime 等于我在墙上看到的时间(即,2015-05-15 4:03:47)。
更新(2)
去掉时间戳:
DateTimeZone utcTZ = DateTimeZone.forTimeZone(TimeZone.getTimeZone("ETC/UTC"));
DateTimeZone localTZ = DateTimeZone.forTimeZone(TimeZone.getTimeZone("America/Montreal"));
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyy-MM-dd HH:mm:ss");
LocalDateTime utcDate = new LocalDateTime(utcTZ);
DateTime utcDateTime = utcDate.toDateTime(utcTZ);
System.out.println("UTC Time: " + utcDateTime);
DateTime dstDateTime = utcDateTime.toDateTime(localTZ);
System.out.println("Unformated Wall Time: " + dstDateTime);
System.out.println("Wall Time: " + dstDateTime.toString(fmt));
输出
UTC Time: 2015-05-20T14:09:28.469Z
Unformated Wall Time: 2015-05-20T10:09:28.469-04:00
Wall Time: 2015-05-20 10:09:28
但是,当我尝试将 UTZ 日期正确到数据库时,一切看起来都很完美, 我需要转换为 Timestamp(即 new Timestamp(o.getOrderDate().getMillis())),它显然是数据库的本地时间,而不是我需要的 UTC Zulu 时间。
提前致谢,
尼克。
【问题讨论】:
-
我还想把“挂墙时间”
2015-05-14 23:22:44放入 Timestamp 对象中。 -
您对更新中的转换没有任何意义。首先,您要打印“UTC 时间”和 java.sql.Timestamp.toString 的输出,但该输出不是 UTC,而是您当地的时区。这将由您没有调用的 TimeZone.setDefault 设置(尽管您正在调用 DateTimeZone.setDefault,因此 Joda-Time 的默认时区与 java.util.Date 不同)。将两个默认值都设置为 UTC,输出应该更有意义。
-
你好阿拉克尼德!非常感谢,现在发送更多。请看我上面的更新。
标签: java datetime jodatime utc