I need to show a date with 2 digits day, 2 digits month, 4 digits year according to the order of the local. So for April 10th 2020
I want to show
- for locale US:
MM/DD/YYYY
->04/10/2020
- for locale UK:
DD/MM/YYYY
->10/04/2020
- for locale DE (Germany):
DD.MM.YYYY
->10.04.2020
I tried the following without success:
// this one already fails for DE, because it gives 10.04.20 (only 2 digit years)
myDate?.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT))
// works for DE (gives 10.04.2020), fails for UK as is gives 10 Apr 2020 instead of 10/04/2020
myDate?.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM))
So, how can I get a locally adapted date format with only 2 digits day/month and 4 digits year? Please note that I am looking for a general solution, the 3 locales explicitly stated here are just examples.
I am actually using a java.time
port for Android (ThreeTenABP
), though this shouldn't be relevant.
Ole V.V.'s answer works from Oreo forwards, but lots of devices are using older versions of Android. The following works in most countries for all Android versions.
This looks hacky, but the official JavaDoc for DateFormat says that casting the format from factory methods to SimpleDateFormat works in majority of countries.
You may wrap that in a try-catch-block and do something clever for the few exceptional countries where this doesn't work. Or for them you could just give up and use their default short format. I'm pretty sure humans can understand that format :-D.