Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best/recommended way to convert Java 8 OffsetDateTime to localized string on android

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?

like image 543
Erik Avatar asked Feb 27 '26 21:02

Erik


1 Answers

org.threeten.bp.format

Forget about DateFormat & Date. Those terrible classes were replaced entirely years ago with the adoption of JSR 310.

See the org.threeten.bp.format package.

DateTimeFormatter

Specifically, 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

Using defaults

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 ) ;
like image 75
Basil Bourque Avatar answered Mar 01 '26 11:03

Basil Bourque



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!