在Java 8中没有获得正确的时区?

fat*_*ael 2 java java-8 java-time

我已将系统数据时间设置为亚洲/加尔各答,它是:

Date: 2015-06-12
Time: 12:07:43.548
Run Code Online (Sandbox Code Playgroud)

现在我在Java 8中编写了以下程序

ZoneId paris = ZoneId.of("Europe/Paris");
LocalDateTime localtDateAndTime = LocalDateTime.now();
ZonedDateTime dateAndTimeInParis  = ZonedDateTime.of(localtDateAndTime, paris );
System.out.println("Current date and time in a particular timezone : " + dateAndTimeInParis  );
Run Code Online (Sandbox Code Playgroud)

当我运行代码时,它会显示巴黎时间:

Current date and time in a particular timezone :    

2015-06-12T12:07:43.548+02:00[Europe/Paris]
Run Code Online (Sandbox Code Playgroud)

上述欧洲/巴黎与亚洲/加尔各答相同.有谁能解释我做错了什么?

更新:我不喜欢使用其他Java包中的类; 因为我听说这个包java.time有足够的功能来处理最大日期时间工作,我希望这个包括:)

Jes*_*per 10

A LocalDateTime是没有时区的日期和时间.当你ZonedDateTime从中创建一个对象时,你明确地将时区附加到了LocalDateTime.

它不会从你的时区转换到Europe/Paris时区; 请注意,LocalDateTime根本没有时区; 它不知道你的意思是它Asia/Kolkata.

如果您想从加尔各答时间转换为巴黎时间,请先ZonedDateTime使用Asia/Kolkata时区:

// Current time in Asia/Kolkata
ZonedDateTime kolkata = ZonedDateTime.now(ZoneId.of("Asia/Kolkata"));

// Convert to the same time in Europe/Paris
ZonedDateTime paris = kolkata.withZoneSameInstant(ZoneId.of("Europe/Paris"));
Run Code Online (Sandbox Code Playgroud)

(编辑,感谢JBNizet):如果您只想及时"现在" Europe/Paris,您可以:

ZonedDateTime paris = ZonedDateTime.now(ZoneId.of("Europe/Paris"));
Run Code Online (Sandbox Code Playgroud)

  • 究竟.OP想要的是`ZonedDateTime.now(ZoneId.of("Europe/Paris"))` (4认同)
  • @JBNizet如果你只想在巴黎时间"现在",这也会奏效. (2认同)