Java already “knows” in which locales the day of month goes before the month name and in which it goes after. This is what the full predefined format gave you. So for a general solution that may work in all or most locales I suggest that you rely on this. We can modify the predefined full pattern to use abbreviations for day of week and for month:
int parseDt = arrayJson.getJSONObject(i-j).getInt("dt"); // dt is a timestamp
Locale locale = ConfigurationCompat.getLocales(Resources.getSystem().getConfiguration()).get(0);
String formatPattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern(
FormatStyle.FULL, null, IsoChronology.INSTANCE, locale);
formatPattern = formatPattern.replaceAll("E{3,}", "EEE").replaceAll("M{3,}", "MMM");
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(formatPattern, locale);
ZoneId zone = ZoneId.of("America/Whitehorse");
ZonedDateTime dateTime = Instant.ofEpochSecond(parseDt).atZone(zone);
String date = dateTime.format(dateFormatter);
System.out.println(date);
Example output:
- In UK locale:
Mon, 2 Jul 2018
- In US locale:
Mon, Jul 2, 2018
- In FRENCH locale:
lun. 2 juil. 2018
I am using regular expressions to make sure that if day of week and/or month is in the format pattern string (for example EEEE
and MMMM
), it is modified to its abbreviation. Since day of week may also be indicated by lowercase e
or c
and month by L
, you may want to do the same trick with these letters.
I am using java.time
, the modern Java date and time API. To use this on not-brand-new Android, get the ThreeTenABP library: use the links at the bottom. If you object to using a high-quality future-proof external library, you may be able to play a similar trick with SimpleDateFormat
.
If you want to omit the year too (as in your examples), it is slightly more complicated, but doable. Here’s a simple attempt to remove the year if it comes last:
formatPattern = formatPattern.replaceFirst("^(.*[\\w'])([^\\w']*y+)$", "$1");
With this line inserted the output in French locale is just lun. 2 juil.
, for example. Year may also be given with letter u
, you may want to take this into account too.
Converting your Unix time to a date is a time zone sensitive operation, so I give time zone in the code. Please put the one you desire where I put America/Whitehorse. If you trust that the JVM’s time zone setting reflects what the user wants, you may use ZoneId.systemDefault()
(the SimpleDateFormat
in your own code uses the VM setting too).
Links