Search code examples
javaandroidsimpledateformatdate-format

Print time-related strings like "today" and "yesterday" translated depending on Locale?


I am looking for a way to print time-related strings like "Today" and "Yesterday" translated to the user's Locale (i.e language) in an Android app.

I have tried to use DateUtils.getRelativeDateTimeString but it does not consider the locale, or at least it is not possible to change it during runtime. I would need something similar to this existing constructor of SimpleDateFormat:

public SimpleDateFormat(String pattern, Locale locale)

Of course, it would be possible to add translations of each word in every language but isn't there a better way assuming the words actually exists in the OS.

Is there a way to achieve this?

Edit: I am trying to do something similar to the date picker on iOS:


Solution

  • With @Meno Hochschild' comment I was able to solve it by:

    1. Adding the Time4A library.
    2. Made a local copy of UnitPatterns.java and made it public.
    3. Used it like this:

    UnitPatterns.of(locale).getTodayWord(); // returns "today" UnitPatterns.of(locale).getYesterdayWord(); // returns "yesterday"