我正在使用 ThreeTen-Backport 将我的 Android 应用程序转换为使用新的 Java 8 日期时间类而不是遗留的 Java Date
类。
根据用户的 Android 偏好设置日期和时间格式以呈现给用户的最佳/推荐方式是什么?在使用 Date
类时,我这样使用了 DateFormat
:
DateFormat.getDateFormat(context).format(new Date()) // for date
DateFormat.getTimeFormat(context).format(new Date()) // for time
这些方法接收一个Date
作为参数。我应该通过将我的 OffsetDateTime
转换为 Date
来继续使用它们,还是有更好的方法来做到这一点?
最佳答案
org.threeten.bp.format
忘掉 DateFormat
和 Date
。那些可怕的类(class)在几年前被 JSR 310 的采用完全取代了。 .
DateTimeFormatter
具体来看DateTimeFormatter
类及其 ofLocalized...
方法。
有关详细信息,请从 java.time 中搜索等效类。格式化已经讲过很多次了。 API 和功能将几乎相同,因此现有的帖子将适用。
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
Locale l = Locale.CANADA_FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM ).withLocale( l ) ;
String output = zdt.format( f ) ;
11 mai 2019
使用默认值
如果你想使用 JVM 的当前默认值 for the time zone或 for the locale ,我建议你明确地这样做。这样任何阅读您代码的人都知道您考虑了区域/区域设置问题并有意识地选择使用默认值。
ZoneId z = ZoneId.systemDefault() ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
Locale l = Locale.getDefault() ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM ).withLocale( l ) ;
String output = zdt.format( f ) ;
关于java - 在 Android 上将 Java 8 OffsetDateTime 转换为本地化字符串的最佳/推荐方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56093455/