我有一个Timestamp对象,我想显示它。
实际上,我使用的是new Timestamp(System.currentTimeMillis()).toLocaleString(),我的结果是:
27d. 2021 17:54:35
但是:
toLocaleString()方法2021年12月27日17:54:35
这不是我想要的。在我的个人电脑里,用法语来说,很好。但是,在VPS上是不好的。
而且,所有被发现的线程都只是在谈论格式化,而没有月名,这不是我想要的。
我怎么能用法语轻松地显示时间戳呢?
发布于 2021-12-27 18:06:48
tl;dr
使用添加到旧类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.
);请参见这段代码在IdeOne.com现场运行。
狂欢节28 décembre 2021à05:39:58
详细信息
Timestamp是一个可怕的遗留日期-时间类。这些类是多年前的被现代取代类。不要使用时间戳、日期、日历、SimpleDateFormat等。
捕捉世界协调时所看到的当前时刻,以零小时-分-秒的偏移.
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中使用符合JDBC4.2或更高版本的JDBC驱动程序的OffsetDateTime类。
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;调整到所需的时区以生成ZonedDateTime对象。
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;所有这些都已经在堆栈溢出上处理了很多次。寻找更多的知识。
https://stackoverflow.com/questions/70498444
复制相似问题