Java8、时间未转换

Java 8, time is not being converted

我正在使用 Hibernate 5 & MySQL。

这是保存到数据库中的内容:2018-03-11 06:26:47.336 我不认为这是 24 小时格式,但是我怎么看 AM/PM?以及如何以 24 小时格式保存时间?

运行 MySQL 中的 SELECT @@global.time_zone; 向我显示: +00:00 所以我想我已经准备好接受 UTC 时间了?这就是我设置时间的 pojo 字段的方式:

Clock clock = Clock.systemUTC();        
LocalDateTime userCreated = LocalDateTime.now(clock);

它接受 LocalDateTime。但是当我查询时我从数据库中得到的是:u1.getUserCreated(): 2018-03-11T01:26:47.336 当我尝试将时间转换为特定区域时,我得到以下信息:

ZonedDateTime z1 = ZonedDateTime.of(u1.getUserCreated(), ZoneId.of("America/New_York"));
System.out.println("z1: " + z1); 
// z1: 2018-03-11T01:26:47.336-05:00[America/New_York]

但它确实应该是:9:26:47.336 PM (21:26:47.336) 正如您在本网站上看到的那样:http://www.timebie.com/std/utc.php

您只是没有正确转换。您的 LocalDateTime 表示 UTC 时区的 wall-clock 时间。不在纽约时区。所以你需要将它转换为 UTC 中的 ZonedDateTime::

ZonedDateTime utcDateTime = u1.getUserCreated().atZone(ZoneOffset.UTC);

然后,如果您想获得同一时刻的 ZonedDateTime,但在纽约时区,那么,就这样做吧:

ZonedDateTime newYorkDateTime = utcDateTime.withZoneSameInstant(ZoneId.of("America/New_York"));