Java 时间:将日期和时间保存到其他时区

Java time: preserve date and time to other timezone

是否可以在其他时区获得相同的日期和时间?

我的意思是,目前,我正在从数据库中获取祖鲁语日期时间。这是:

2019-04-02T00:00:00Z

我需要将日期和时间部分保留在其他时区 (ZoneId.systemDefault())。我想得到:

2019-04-02T00:00:00+02:00[Europe/Madrid]

能拿到吗?

当然,这是可能的,而且很容易做到。

final String dateStr = "2019-04-02T00:00:00Z";
final ZonedDateTime date = ZonedDateTime.parse(dateStr);
final ZonedDateTime zonedDateTime = date.withZoneSameLocal(ZoneId.systemDefault());

输出:

date:          2019-04-02T00:00Z
zonedDateTime: 2019-04-02T00:00+02:00[Europe/Rome]

withZoneSameLocal 正在施展魔法

Returns a copy of this date-time with a different time-zone, retaining the local date-time if possible.