tl;博士
ZonedDateTime.now( // Capture the current moment as seen with a wall-clock time used by the people of a certain region (a time zone).
ZoneId.of( "America/Los_Angeles" ) // Use proper time zone names in `continent/region` format. Never use pseudo-zones such as `PST` & `EST`.
).withZoneSameInstant( // Adjust from one zone to another. Using immutable objects, so we produce a second distinct `ZonedDateTime` object.
ZoneId.of( "America/New_York" ) // Same moment, different wall-clock time.
)
java.time和ThreeTen-Backport
要获得Java 7中的大部分java.time功能,请将ThreeTen-Backport库添加到项目中 .
通常最好使用UTC值 .
Instant instant = Instant.now() ; // Capture the current moment in UTC.
仅在business logic需要时应用时区或显示给用户 .
您的 PST 和 EST 值不是实际时区 . 使用proper time zone names .
ZoneId z = ZoneId.of( "America/Los_Angeles" ) ;
应用于Instant以获取ZonedDateTime对象 . 同一时刻,时间轴上的同一点,不同的挂钟时间 .
ZonedDateTime zdt = instant.atZone( z ) ;
调整到另一个时区 . java.time框架使用immutable objects . 因此,我们不是改变(“改变”)原始的,而是根据原始值生成一个单独的不同对象 .
ZonedDateTime 对象和 Instant all represent the very same moment ,时间轴上的相同点 . 这是在日期时间处理中理解的关键概念 . 想象一下两个人,一个在西海岸,一个在北美东海岸,通过电话互相交谈 . 如果他们同时抬头看着挂在各自墙上的钟,他们什么时候看?同一时刻,不同的挂钟时间 .
ZoneId zNewYork = ZoneId.of( "America/New_York" ) ;
ZonedDateTime zdtNewYork = zdt.withZoneSameInstant( zNewYork ) ; // Same moment, different wall-clock time.
Stack Overflow上已经涵盖了很多次这一切 . 因此,寻找更多的例子和讨论 .
关于java.time
要了解更多信息,请参阅Oracle Tutorial . 并搜索Stack Overflow以获取许多示例和解释 . 规格是JSR 310 .
您可以直接与数据库交换java.time对象 . 使用JDBC driver符合JDBC 4.2或更高版本 . 不需要字符串,不需要 java.sql.* 类 .
从哪里获取java.time类?
内置 .
具有捆绑实现的标准Java API的一部分 .
Java 9增加了一些小功能和修复 .
大部分java.time功能在ThreeTen-Backport中反向移植到Java 6和7 .
更新版本的Android捆绑java.time类的实现 .
对于早期的Android(<26),ThreeTenABP项目采用ThreeTen-Backport(如上所述) . 见How to use ThreeTenABP… .
ThreeTen-Extra项目使用其他类扩展java.time . 该项目是未来可能添加到java.time的试验场 . 您可以在这里找到一些有用的类,例如Interval,YearWeek,YearQuarter和more .