In English the time format "h:mm a" gives "8:32 AM." In Spanish the same time format "h:mm a" gives me "8:32 a. m." Is there an easy way to format the Spanish to look like the English? Can you force a format to AM/PM in caps in Android/Java?
Asked
Active
Viewed 125 times
1 Answers
0
Easy solution: Specify a locale that uses upper case AM and PM. For example:
DateTimeFormatter formatter = DateTimeFormatter
.ofLocalizedTime(FormatStyle.SHORT)
.withLocale(Locale.US);
LocalTime time = LocalTime.of(8, 32);
String withUpperCaseAmPm = time.format(formatter);
System.out.println(withUpperCaseAmPm);
Output is:
8:32 AM
I am of course using java.time, the modern Java date and time API.
Hard solution: Specify the texts AM
and PM
explicitly.
Map<Long, String> amPmTexts = new HashMap<>();
amPmTexts.put(0L, "AM");
amPmTexts.put(1L, "PM");
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("h:mm ")
.appendText(ChronoField.AMPM_OF_DAY, amPmTexts)
.toFormatter();
When using this formatter instead output is the same as before.
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
- Oracle tutorial: Date Time explaining how to use java.time.
- Java Specification Request (JSR) 310, where
java.time
was first described. - ThreeTen Backport project, the backport of
java.time
to Java 6 and 7 (ThreeTen for JSR-310). - Java 8+ APIs available through desugaring
- ThreeTenABP, Android edition of ThreeTen Backport
- Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

Ole V.V.
- 81,772
- 15
- 137
- 161