离开几年后,我开始学习Java编程。我注意到Java 8中有一些新的date/time对象。
对于使用Java8的持久化数据bean,我应该为日期/时间属性使用什么类型?是Instant、ZoneDateTime还是Date
发布于 2017-06-20 21:32:11
首先,您应该避免使用旧的类(Date、Calendar和SimpleDateFormat)。它们有lots of problems和design issues,其中大多数都是由新的API修复的(这就是创建新类的原因)。
在IMO中,最好在 UTC 中内部使用date/time对象-最好的类是Instant,它总是在UTC中。因此,为了在数据库中持久化并执行内部操作,我总是更喜欢使用UTC日期/时间,因为它使事情不那么混乱,并避免所有时间都进行不必要的转换。
当/如果您需要向用户或在其他界面中显示此日期/时间,并且您希望它位于特定时区,则将此Instant转换为ZonedDateTime。
示例:
// create current instant in UTC - Instant is **always** in UTC
Instant now = Instant.now();
System.out.println(now); // 2017-06-20T13:28:39.075Z
// converting to some timezone
ZonedDateTime z = now.atZone(ZoneId.of("America/Sao_Paulo"));
System.out.println(z); // 2017-06-20T10:28:39.075-03:00[America/Sao_Paulo]
// converting to another timezone
z = now.atZone(ZoneId.of("Europe/London"));
System.out.println(z); // 2017-06-20T14:28:39.075+01:00[Europe/London]
// converting back to Instant
System.out.println(z.toInstant()); // 2017-06-20T13:28:39.075Z因此,UTC时刻是2017-06-20T13:28:39.075Z,它对应于圣保罗的2017-06-20T10:28:39.075-03:00和伦敦的2017-06-20T14:28:39.075+01:00 (请注意,ZoneId已经处理了夏令时的更改)。
还要注意,我使用了完整的时区名称(America/Sao_Paulo和Europe/London)。这些Continent/City格式的名称由IANA database定义,并由新的API使用。
您应该避免使用3个字母的时区名称(如ECT或CST),因为它们是ambiguous and not standard。总是喜欢使用全名-您可以通过调用ZoneId.getAvailableZoneIds()来获取所有可用的名称。
您也可以使用ZoneId.systemDefault() -这将在您的系统中配置默认时区。但这可以在运行时更改,从而导致不可预测的结果,因此使用显式时区总是更好的。
上面的输出是每个对象的toString()方法的结果。但是如果你想要不同的格式,你可以使用DateTimeFormatter类:
ZonedDateTime z = now.atZone(ZoneId.of("America/Sao_Paulo"));
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss xxx");
System.out.println(fmt.format(z)); // 20/06/2017 10:28:39 -03:00请参考javadoc查看所有可能的格式。
发布于 2017-06-20 21:32:41
我希望bean中的属性在UTC中是Instant的,无论在哪里需要将其呈现给客户端,都可以将其转换为适当的ZonedDateTime。
Instant instant = Instant.now() ; // gives current instant of time in UTC.
//Can be converted to ZonedDateTime
ZoneId zone = ZoneId.of( "Asia/Kolkata" ) ) ;
ZonedDateTime zdt = instant.atZone( zone ) ;https://stackoverflow.com/questions/44653435
复制相似问题