Java时间:保留其他时区的日期和时间

问题描述 投票:2回答:1

是否能够在其他时区获得相同的日期时间?

我的意思是,目前,我从数据库获得了zulu日期时间。这是:

2019-04-02T00:00:00Z

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

2019-04-02T00:00:00 + 02:00 [欧洲/马德里]

它能够得到它吗?

java java-time
1个回答
4
投票

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

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正在做着魔术

使用不同的时区返回此日期时间的副本,如果可能,保留本地日期时间。

© www.soinside.com 2019 - 2024. All rights reserved.