2017-02-16 81 views
2

假设一个星期前我生成2015-10-10T10:00:00的LocalDateTime。此外,让我们假设我生成我当前时区ID这样根据当前时区与东部时区的时差,更改LocalDateTime

TimeZone timeZone = TimeZone.getDefault(); 
String zoneId = timeZone.getId(); // "America/Chicago" 

而我是了zoneid“美国/芝加哥”。

有没有一种简单的方法,我可以将我的LocalDateTime转换为时区ID为“America/New_York”的一个(即我的更新LocalDateTime将2015-10-10T11:00:00)?

更重要的是,有没有一种方法可以将我的LocalDateTime转换为东部时间(即,到zoneId为“America/New_York”的时区),无论我在哪个时区?我特意寻找一种方法来处理过去生成的任何LocalDateTime对象,而不是在当前时间。

+0

'LocalDateTime.now(ZoneId.of( “美国/纽约”));' –

+0

对不起,我专门寻找一种方式来生成基于一个LocalDateTime,我可以有时间过去产生。这只会得到当前的LocalDateTime。 –

回答

3

要将LocalDateTime转换到另一个时区,你先申请使用atZone()原来的时区,它返回一个ZonedDateTime,然后转换为使用withZoneSameInstant()新的时区,最后的结果转换回LocalDateTime

LocalDateTime oldDateTime = LocalDateTime.parse("2015-10-10T10:00:00"); 
ZoneId oldZone = ZoneId.of("America/Chicago"); 

ZoneId newZone = ZoneId.of("America/New_York"); 
LocalDateTime newDateTime = oldDateTime.atZone(oldZone) 
             .withZoneSameInstant(newZone) 
             .toLocalDateTime(); 
System.out.println(newDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)); 
2015-10-10T11:00:00 

如果跳过最后一步,你会保留区。

ZonedDateTime newDateTime = oldDateTime.atZone(oldZone) 
             .withZoneSameInstant(newZone); 
System.out.println(newDateTime.format(DateTimeFormatter.ISO_DATE_TIME)); 
2015-10-10T11:00:00-04:00[America/New_York]