tl;博士
使用Instant 类,它总是在UTC 中。所以time zone 不再是问题。
someInstant.isBefore( Instant.now() )
java.time
现代方法使用 java.time 类取代了可怕的 Date 和 Calendar 类。
正如correct Answer by Kuo 所说,您的java.util.Date 正在记录UTC 时刻。所以不需要时区。
同样,它的替代品 java.time.Instant 类也记录了 UTC 时刻。所以不需要时区。
Instant instant = Instant.now() ; // Capture current in UTC.
因此,作为类的成员变量,您只需要Instant。
public class Event {
Instant when ;
…
}
要比较Instant 对象,请使用isAfter、isBefore 和equals 方法。
someInstant.isBefore( Instant.now() )
对于在用户期望的时区进行演示,分配一个ZoneId 以获取一个ZonedDateTime 对象。 Instant 和 ZonedDateTime 都代表同一时刻,时间轴上的同一点,但通过不同的挂钟时间查看。
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z ) ; // Same moment, different wall-clock time.
String output = zdt.toString() ; // Generate text in standard ISO 8601 format, wisely extended to append the name of the zone in square brackets.
或者让java.time自动本地化输出。要进行本地化,请指定:
例子:
Locale l = Locale.CANADA_FRENCH ; // Or Locale.US, Locale.JAPAN, etc.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL )
.withLocale( l );
String output = zdt.format( f );
关于java.time
java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.Date、Calendar 和 SimpleDateFormat。
Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。
要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310。
您可以直接与您的数据库交换 java.time 对象。使用符合JDBC 4.2 或更高版本的JDBC driver。不需要字符串,不需要java.sql.* 类。
从哪里获得 java.time 类?
ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是未来可能添加到 java.time 的试验场。您可以在这里找到一些有用的类,例如Interval、YearWeek、YearQuarter 和more。