tl;博士
使用添加到旧类Timestamp 的新转换方法来转换为现代java.time 类。
Timestamp myTimestamp = Timestamp.from( Instant.now() ); // Simulate receiving a `Timestamp` object from old code not yet updated to *java.time*.
System.out.println(
myTimestamp
.toInstant() // Convert from legacy class to modern class.
.atZone( // Adjust into a time zone.
ZoneId.of( "Asia/Tokyo" )
) // Returns a `ZonedDateTime` object.
.format(
DateTimeFormatter
.ofLocalizedDateTime(
FormatStyle.FULL
)
.withLocale(
Locale.FRANCE
)
) // Returns a `String` object, generated text.
);
查看此代码run live at IdeOne.com。
狂欢节 2021 年 12 月 28 日 à 05:39:58 heure normale du Japon
详情
Timestamp 是可怕的遗留日期时间类之一。这些课程是几年前的supplanted by the modern java.time 课程。切勿使用 Timestamp、Date、Calendar、SimpleDateFormat 等。
以 UTC 格式捕捉当前时刻,偏移量为零时分秒。
Instant instant = Instant.now() ;
捕捉特定时区的当前时刻。
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
以自动本地化格式生成文本。指定语言环境以确定翻译中使用的人类语言以及缩写、大写、元素顺序等中使用的文化规范。
Locale locale = Locale.CANADA_FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM ).withLocale( locale ) ;
String output = zdt.format( f ) ;
如果从类似于 SQL 标准类型 TIMESTAMP WITH TIME ZONE 的数据类型的数据库列接收时刻,请使用 Java 中的 OffsetDateTime 类和符合 JDBC 4.2 或更高版本的 JDBC 驱动程序。
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
调整到您想要的时区以生成 ZonedDateTime 对象。
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;
所有这些都已经在 Stack Overflow 上处理过很多次了。搜索以了解更多信息。