Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force Android DateUtils.getRelativeDateTimeString() to ignore the device locale?

I've found using the android.text.format.DateUtils relative APIs that return values like "yesterday" or "2 hours ago" very nice - but my app does not support every language Android does. So, I default to English, but for every language I don't support, the relative string shows in the device's setting.

For example, like:

Last attempt: hace 11 minutos.

I'd like to make the API call default to English for any languages I don't support. However, I don't see anywhere to set the Locale for the API call - I'm hoping I'm just missing it somewhere.

Is there a way to set the Locale just for the API call, ignoring the device setting?

like image 776
Eric Avatar asked Jun 30 '11 18:06

Eric


2 Answers

This is working for me up to Android 7

  void forceLocale(Locale locale) {
    Configuration conf = getBaseContext().getResources().getConfiguration();
    updateConfiguration(conf, locale);
    getBaseContext().getResources().updateConfiguration(conf, getResources().getDisplayMetrics());

    Configuration systemConf = Resources.getSystem().getConfiguration();
    updateConfiguration(systemConf, locale);
    Resources.getSystem().updateConfiguration(conf, getResources().getDisplayMetrics());

    Locale.setDefault(locale);
  }

  void updateConfiguration(Configuration conf, Locale locale) {
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){
      conf.setLocale(locale);
    }else {
      //noinspection deprecation
      conf.locale = locale;
    }
  }
like image 150
Maragues Avatar answered Nov 12 '22 21:11

Maragues


According to the source code of the DateUtils class it uses both Resource.getSystem() and Locale.getDefault() method for formatting date and time. You can change the default Locale using Locale.setDefault() method but I don't think it's possible to change the return value of the Resource.getSystem() method. You can try to change the default locale to Locale.US but it seems to me that results will be even worse in this case.

like image 36
Michael Avatar answered Nov 12 '22 21:11

Michael