I am trying to display date and time including seconds BUT formatted according to user's locale settings. So if an action happened on the 5th of March 2020 at 14:47:51, in US it should be displayed as 03/05/2020 14:47:51
while in UK it would be 05/03/2020 14:47:51
, in Poland 05.03.2020, 14:47:51
, in Czechia 5.3.2020 14:47:51
etc.
I am able to display it without seconds by:
DateUtils.formatDateTime(
context,
event.time,
DateUtils.FORMAT_24HOUR or DateUtils.FORMAT_SHOW_TIME or DateUtils.FORMAT_SHOW_YEAR or DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_NUMERIC_DATE
)
But there is no constant to display seconds.
Any ideas, please?
DateTimeFormatter localizedFormatter = DateTimeFormatter
.ofLocalizedDateTime(FormatStyle.SHORT, FormatStyle.MEDIUM);
ZonedDateTime dateTime = ZonedDateTime
.of(2020, 3, 5, 14, 47, 51, 123456789, ZoneId.systemDefault());
System.out.println(dateTime.format(localizedFormatter));
My desktop Java 11 gets its locale data from CLDR, the Unicode Common Locale Data Repository , used by default as of Java 9 . These data don't agree with your expectations in all cases. Output in different locales is:
en-US 3/5/20, 2:47:51 PM
en-GB 05/03/2020, 14:47:51
pl-PL 05.03.2020, 14:47:51
cs-CZ 05.03.20 14:47:51
See this run live on Java 12 at IdeOne.com .
Output on Android may differ, though, please see for yourself if you don't get satisfactory results.
The two-argument DateTimeFormatter.ofLocalizedDateTime()
takes one argument for date style and one for time style. Each can be short, medium, long or full.
java.time works nicely on both older and newer Android devices. It just requires at least Java 6 .
org.threeten.bp
with subpackages.java.time
was first described. java.time
to Java 6 and 7 (ThreeTen for JSR-310).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.