简体   繁体   中英

Format date and time with seconds while using user's locale settings

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?

java.time

    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.

Question: Doesn't java.time require Android API level 26?

java.time works nicely on both older and newer Android devices. It just requires at least Java 6 .

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On older Android either use desugaring or the Android edition of ThreeTen Backport. It's called ThreeTenABP. In the latter case make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM