I'm converting my Android app to use the new Java 8 date time classes using the ThreeTen-Backport instead of the legacy Java Date class.
What would be the best/recommended way to format the date and time to present to the user based on the user's Android preferences? While using the Date class, I used the DateFormat as such:
DateFormat.getDateFormat(context).format(new Date()) // for date
DateFormat.getTimeFormat(context).format(new Date()) // for time
These methods receive a Date as the parameter. Should I continue to use them by converting my OffsetDateTime to Date or is there a better way to do it?
org.threeten.bp.formatForget about DateFormat & Date. Those terrible classes were replaced entirely years ago with the adoption of JSR 310.
See the org.threeten.bp.format package.
DateTimeFormatterSpecifically, look at the DateTimeFormatter class and its ofLocalized… methods.
For more info, search for the equivalent classes from java.time. Formatting has been covered many many times already. The API and functionality will be nearly identical, so the existing posts will apply.
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
If you want to use the JVM’s current default values for the time zone or for the locale, I suggest you do so explicitly. This way anyone reading your code knows you considered the zone/locale issues and consciously chose to use the default.
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 ) ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With