提问人:nullUser 提问时间:7/25/2019 更新时间:7/26/2019 访问量:735
将时区添加到打印格式的 ZonedDateTime
ZonedDateTime with timezone added to print format
问:
我正在我的项目中使用 https://github.com/JakeWharton/ThreeTenABP。
我有org.threeten.bp
ZonedDate时间: 2019-07-25T 14:30:57+05:30[Asia/Calcutta]
我怎样才能在添加时区小时的情况下打印出来?即结果应该有 2019-07-25T20:00:57
答:
2赞
Ryuzaki L
7/26/2019
#1
以秒的形式获取偏移量ZonedDateTime
ZonedDateTime time = ZonedDateTime.parse("2019-07-25T14:30:57+05:30");
long seconds = time.getOffset().getTotalSeconds();
现在从中获取零件LocalDateTime
ZonedDateTime
LocalDateTime local = time.toLocalDateTime().plusSeconds(seconds); //2019-07-25T20:00:57
toLocalDateTime
获取此日期时间的 LocalDateTime 部分。
如果要获取 UTC 中的本地日期时间,请使用toInstant()
这将返回一个 Instant,表示时间轴上与此日期时间相同的点。该计算结合了本地日期时间和偏移量。
Instant i = time.toInstant(); //2019-07-25T09:00:57Z
2赞
Anonymous
7/26/2019
#2
你误会了。字符串中 +05:30 的偏移量表示与 UTC 相比,时间已添加 5 小时 30 分钟。因此,再次添加它们将没有任何意义。
如果要补偿偏移量,只需将日期时间转换为UTC即可。例如:
ZonedDateTime zdt = ZonedDateTime.parse("2019-07-25T14:30:57+05:30[Asia/Calcutta]");
OffsetDateTime utcDateTime = zdt.toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC);
System.out.println(utcDateTime);
输出:
2019-07-25T09:00:57Z
评论
+00:00
2019-07-25T09:00:57+00:00