我使用:System.currentTimeMillis
获取当前毫秒/unix 时间
不要这样做。
Instant.now() 方法取代了那个过时的方法。此外,Instant 能够实现更精细的粒度,最高可达纳秒级。目前,OpenJDK 中的实现以微秒为单位捕获当前时刻,比其他方法的毫秒更精细。
Instant instant = Instant.now() ;
instant.toString(): 2019-07-27T02:15:34.727766Z
现在我想将此长值转换为特定时区。
将您的时区指定为ZoneId。申请Instant 以获取ZonedDateTime。
ZoneId z = ZoneId.of( "America/New_York" ) ; // Or did you have another zone in mind, such as `America/Montreal` ?
ZonedDateTime zdt = instant.atZone( z );
或者,您可以跳过Instant。在传递ZoneId 时调用ZonedDateTime.now。
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
特定时区,例如美国东部标准时间 -5(纽约)。
EST 不是真正的时区。
以Continent/Region 的格式指定proper time zone name,例如America/Montreal、Africa/Casablanca 或Pacific/Auckland。切勿使用 2-4 个字母的缩写,例如 EST 或 IST,因为它们不是真正的时区,没有标准化,甚至不是唯一的 (!)。
我如何使用 Joda time 做到这一点,因为我听说这是最好的库,但 API 对我来说似乎有点混乱。
Joda-Time 项目现在由 JSR 310 定义的 Java 8 及更高版本中内置的 java.time 类继承。Android 26 及更高版本具有这些类也。
您对写入数据库的评论。如果您的数据库具有正确的日期时间类型,请使用它们而不是存储长整数。
从 JDBC 4.2 开始,我们可以与数据库交换 java.time 对象。
我们在这里讨论的时刻应该存储在类似于 SQL 标准类型TIMESTAMP WITH TIME ZONE(WITH,不是WITHOUT!)的数据类型的列中。
奇怪的是,JDBC 规范只要求支持OffsetDateTime,而不是Instant 或ZonedDateTime。所以,转换吧。
myPreparedStatement.setObject( … , zdt.toOffsetDateTime() ) ;
检索。
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ; // Adjust to a time zone.
Instant instant = zdt.toInstant() ; // Adjust to UTC.
OffsetDateTime 和 ZonedDateTime 有什么区别?
- 与 UTC 的偏移量只是几个小时-分钟-秒。仅此而已。
- 时区更多。时区是特定地区的人们使用的偏移量的过去、现在和未来变化的历史。